GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1 lines
4.7 MiB

{"version":3,"file":"firebase-compat.js","sources":["../util/src/crypt.ts","../util/src/constants.ts","../util/src/assert.ts","../util/src/deepCopy.ts","../util/src/global.ts","../util/src/defaults.ts","../logger/src/logger.ts","../../node_modules/idb/build/index.js","../util/src/deferred.ts","../util/src/emulator.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/json.ts","../util/src/jwt.ts","../util/src/obj.ts","../util/src/query.ts","../util/src/sha1.ts","../util/src/subscribe.ts","../util/src/validation.ts","../util/src/uuid.ts","../util/src/utf8.ts","../util/src/exponential_backoff.ts","../util/src/compat.ts","../component/src/component.ts","../component/src/constants.ts","../component/src/provider.ts","../component/src/component_container.ts","../../node_modules/idb/build/wrap-idb-value.js","../app/src/platformLoggerService.ts","../app/src/logger.ts","../app/src/registerCoreComponents.ts","../app/src/constants.ts","../app/src/internal.ts","../app/src/errors.ts","../app/src/firebaseApp.ts","../app/src/api.ts","../app/src/indexeddb.ts","../app/src/heartbeatService.ts","../app/src/index.ts","../app-compat/src/firebaseApp.ts","../app-compat/src/errors.ts","../app-compat/src/firebaseNamespaceCore.ts","../app-compat/src/firebaseNamespace.ts","../app-compat/src/logger.ts","../app-compat/src/index.ts","../app-compat/src/registerCoreComponents.ts","compat/app/index.ts","../installations/src/util/constants.ts","../installations/src/util/errors.ts","../installations/src/functions/common.ts","../installations/src/util/sleep.ts","../installations/src/helpers/generate-fid.ts","../installations/src/helpers/buffer-to-base64-url-safe.ts","../installations/src/util/get-key.ts","../installations/src/helpers/fid-changed.ts","../installations/src/helpers/idb-manager.ts","../installations/src/helpers/get-installation-entry.ts","../installations/src/functions/create-installation-request.ts","../installations/src/functions/generate-auth-token-request.ts","../installations/src/helpers/refresh-auth-token.ts","../installations/src/api/get-token.ts","../installations/src/helpers/extract-app-config.ts","../installations/src/functions/config.ts","../installations/src/api/get-id.ts","../installations/src/index.ts","../analytics/src/constants.ts","../analytics/src/logger.ts","../analytics/src/helpers.ts","../analytics/src/errors.ts","../analytics/src/get-config.ts","../analytics/src/initialize-analytics.ts","../analytics/src/factory.ts","../analytics/src/api.ts","../analytics/src/functions.ts","../analytics/src/index.ts","../analytics-compat/src/constants.ts","../analytics-compat/src/index.ts","../analytics-compat/src/service.ts","../app-check/src/state.ts","../app-check/src/constants.ts","../app-check/src/proactive-refresh.ts","../app-check/src/errors.ts","../app-check/src/util.ts","../app-check/src/client.ts","../app-check/src/indexeddb.ts","../app-check/src/logger.ts","../app-check/src/storage.ts","../app-check/src/debug.ts","../app-check/src/internal-api.ts","../app-check/src/factory.ts","../app-check/src/recaptcha.ts","../app-check/src/providers.ts","../app-check/src/api.ts","../app-check/src/index.ts","../app-check-compat/src/errors.ts","../app-check-compat/src/service.ts","../app-check-compat/src/index.ts","../../node_modules/tslib/tslib.es6.js","../auth/src/model/enum_maps.ts","../auth/src/core/errors.ts","../auth/src/core/util/log.ts","../auth/src/core/util/assert.ts","../auth/src/core/util/instantiator.ts","../auth/src/core/util/location.ts","../auth/src/core/util/delay.ts","../auth/src/core/util/navigator.ts","../auth/src/core/util/emulator.ts","../auth/src/core/util/fetch_provider.ts","../auth/src/api/errors.ts","../auth/src/api/index.ts","../auth/src/core/util/time.ts","../auth/src/core/user/id_token_result.ts","../auth/src/core/user/invalidation.ts","../auth/src/core/user/proactive_refresh.ts","../auth/src/core/user/user_metadata.ts","../auth/src/core/user/reload.ts","../auth/src/api/account_management/account.ts","../auth/src/core/user/token_manager.ts","../auth/src/api/authentication/token.ts","../auth/src/core/user/user_impl.ts","../auth/src/core/persistence/in_memory.ts","../auth/src/core/persistence/persistence_user_manager.ts","../auth/src/core/util/browser.ts","../auth/src/core/util/version.ts","../auth/src/core/auth/middleware.ts","../auth/src/core/auth/auth_impl.ts","../auth/src/core/auth/emulator.ts","../auth/src/core/credentials/auth_credential.ts","../auth/src/api/account_management/email_and_password.ts","../auth/src/api/authentication/email_and_password.ts","../auth/src/core/credentials/email.ts","../auth/src/api/authentication/email_link.ts","../auth/src/api/authentication/idp.ts","../auth/src/core/credentials/oauth.ts","../auth/src/api/authentication/sms.ts","../auth/src/core/credentials/phone.ts","../auth/src/core/action_code_url.ts","../auth/src/core/providers/email.ts","../auth/src/core/providers/federated.ts","../auth/src/core/providers/oauth.ts","../auth/src/core/providers/facebook.ts","../auth/src/core/providers/google.ts","../auth/src/core/providers/github.ts","../auth/src/core/credentials/saml.ts","../auth/src/core/providers/saml.ts","../auth/src/core/providers/twitter.ts","../auth/src/api/authentication/sign_up.ts","../auth/src/core/user/user_credential_impl.ts","../auth/src/mfa/mfa_error.ts","../auth/src/core/util/providers.ts","../auth/src/core/user/link_unlink.ts","../auth/src/core/user/reauthenticate.ts","../auth/src/core/strategies/credential.ts","../auth/src/core/strategies/custom_token.ts","../auth/src/api/authentication/custom_token.ts","../auth/src/mfa/mfa_info.ts","../auth/src/core/strategies/action_code_settings.ts","../auth/src/core/strategies/email_and_password.ts","../auth/src/core/strategies/email_link.ts","../auth/src/core/strategies/email.ts","../auth/src/api/authentication/create_auth_uri.ts","../auth/src/core/user/account_info.ts","../auth/src/api/account_management/profile.ts","../auth/src/core/user/additional_user_info.ts","../auth/src/mfa/mfa_session.ts","../auth/src/mfa/mfa_resolver.ts","../auth/src/mfa/mfa_user.ts","../auth/src/api/account_management/mfa.ts","../auth/src/core/persistence/index.ts","../auth/src/platform_browser/persistence/browser.ts","../auth/src/platform_browser/persistence/local_storage.ts","../auth/src/platform_browser/persistence/session_storage.ts","../auth/src/platform_browser/messagechannel/receiver.ts","../auth/src/platform_browser/messagechannel/promise.ts","../auth/src/core/util/event_id.ts","../auth/src/platform_browser/messagechannel/sender.ts","../auth/src/platform_browser/auth_window.ts","../auth/src/platform_browser/util/worker.ts","../auth/src/platform_browser/persistence/indexed_db.ts","../auth/src/platform_browser/load_js.ts","../auth/src/platform_browser/recaptcha/recaptcha_mock.ts","../auth/src/platform_browser/recaptcha/recaptcha_loader.ts","../auth/src/platform_browser/recaptcha/recaptcha_verifier.ts","../auth/src/api/authentication/recaptcha.ts","../auth/src/platform_browser/strategies/phone.ts","../auth/src/api/authentication/mfa.ts","../auth/src/platform_browser/providers/phone.ts","../auth/src/core/util/resolver.ts","../auth/src/core/strategies/idp.ts","../auth/src/core/strategies/abstract_popup_redirect_operation.ts","../auth/src/platform_browser/strategies/popup.ts","../auth/src/core/strategies/redirect.ts","../auth/src/platform_browser/strategies/redirect.ts","../auth/src/core/auth/auth_event_manager.ts","../auth/src/api/project_config/get_project_config.ts","../auth/src/core/util/validate_origin.ts","../auth/src/platform_browser/iframe/gapi.ts","../auth/src/platform_browser/iframe/iframe.ts","../auth/src/platform_browser/util/popup.ts","../auth/src/core/util/handler.ts","../auth/src/platform_browser/popup_redirect.ts","../auth/src/platform_browser/mfa/assertions/phone.ts","../auth/src/mfa/mfa_assertion.ts","../auth/src/core/auth/firebase_internal.ts","../auth/src/platform_browser/index.ts","../auth/src/core/auth/register.ts","../auth/src/platform_cordova/plugins.ts","../auth/src/core/auth/initialize.ts","../auth/src/platform_cordova/popup_redirect/utils.ts","../auth/src/platform_cordova/popup_redirect/events.ts","../auth/src/platform_cordova/popup_redirect/popup_redirect.ts","../auth-compat/index.ts","../auth-compat/src/platform.ts","../auth-compat/src/persistence.ts","../auth-compat/src/popup_redirect.ts","../auth-compat/src/wrap.ts","../auth-compat/src/user_credential.ts","../auth-compat/src/user.ts","../auth-compat/src/auth.ts","../auth/internal/index.ts","../auth/src/core/strategies/anonymous.ts","../auth-compat/src/phone_auth_provider.ts","../auth-compat/src/recaptcha_verifier.ts","../database/src/core/version.ts","../database/src/core/storage/DOMStorageWrapper.ts","../database/src/core/storage/MemoryStorage.ts","../database/src/core/storage/storage.ts","../database/src/core/snap/snap.ts","../database/src/core/snap/indexes/PriorityIndex.ts","../database/src/core/operation/Operation.ts","../database/src/core/SyncPoint.ts","../database/src/core/SyncTree.ts","../database/src/register.ts","../database/src/core/util/util.ts","../database/src/core/AppCheckTokenProvider.ts","../database/src/core/AuthTokenProvider.ts","../database/src/realtime/Constants.ts","../database/src/core/RepoInfo.ts","../database/src/core/stats/StatsCollection.ts","../database/src/core/stats/StatsManager.ts","../database/src/realtime/polling/PacketReceiver.ts","../database/src/realtime/BrowserPollConnection.ts","../database/src/realtime/WebSocketConnection.ts","../database/src/realtime/TransportManager.ts","../database/src/realtime/Connection.ts","../database/src/core/ServerActions.ts","../database/src/core/util/EventEmitter.ts","../database/src/core/util/OnlineMonitor.ts","../database/src/core/util/Path.ts","../database/src/core/util/VisibilityMonitor.ts","../database/src/core/PersistentConnection.ts","../database/src/core/snap/Node.ts","../database/src/core/snap/indexes/Index.ts","../database/src/core/snap/indexes/KeyIndex.ts","../database/src/core/util/SortedMap.ts","../database/src/core/snap/comparators.ts","../database/src/core/snap/LeafNode.ts","../database/src/core/snap/childSet.ts","../database/src/core/snap/IndexMap.ts","../database/src/core/snap/ChildrenNode.ts","../database/src/core/snap/nodeFromJSON.ts","../database/src/core/snap/indexes/PathIndex.ts","../database/src/core/snap/indexes/ValueIndex.ts","../database/src/core/view/Change.ts","../database/src/core/view/filter/IndexedFilter.ts","../database/src/core/view/filter/RangedFilter.ts","../database/src/core/view/filter/LimitedFilter.ts","../database/src/core/view/QueryParams.ts","../database/src/core/ReadonlyRestClient.ts","../database/src/core/SnapshotHolder.ts","../database/src/core/SparseSnapshotTree.ts","../database/src/core/stats/StatsListener.ts","../database/src/core/stats/StatsReporter.ts","../database/src/core/operation/AckUserWrite.ts","../database/src/core/operation/ListenComplete.ts","../database/src/core/operation/Overwrite.ts","../database/src/core/operation/Merge.ts","../database/src/core/view/CacheNode.ts","../database/src/core/view/EventGenerator.ts","../database/src/core/view/ViewCache.ts","../database/src/core/util/ImmutableTree.ts","../database/src/core/CompoundWrite.ts","../database/src/core/WriteTree.ts","../database/src/core/view/ChildChangeAccumulator.ts","../database/src/core/view/CompleteChildSource.ts","../database/src/core/view/ViewProcessor.ts","../database/src/core/view/View.ts","../database/src/core/util/ServerValues.ts","../database/src/core/util/Tree.ts","../database/src/core/util/validation.ts","../database/src/core/view/EventQueue.ts","../database/src/core/Repo.ts","../database/src/core/util/libs/parser.ts","../database/src/core/util/NextPushId.ts","../database/src/core/view/Event.ts","../database/src/core/view/EventRegistration.ts","../database/src/api/OnDisconnect.ts","../database/src/api/Reference_impl.ts","../database/src/api/Database.ts","../database/src/api/ServerValue.ts","../database/src/api/Transaction.ts","../database/src/api/test_access.ts","../database-compat/src/util/util.ts","../database-compat/src/api/onDisconnect.ts","../database-compat/src/api/TransactionResult.ts","../database-compat/src/api/Reference.ts","../database-compat/src/util/validation.ts","../database-compat/src/api/Database.ts","../database-compat/src/index.ts","../database-compat/src/api/internal.ts","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/base.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/disposable.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/array/array.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/event.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserfeature.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/internal.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/reflect/reflect.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/useragent/useragent.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/browser.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xhrio.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserevent.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtype.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenable.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenablekey.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listener.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenermap.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/object/object.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/events.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtarget.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/json.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/workqueue.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/run.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/freelist.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throwexception.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/timer/timer.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throttle.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventhandler.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/requeststats.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/errorcode.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/eventtype.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttpfactory.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttp.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/environment.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/uri.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/dispose.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wirev8.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/string.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/structs/structs.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/utils.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wire.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/functions/functions.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/nativejsonprocessor.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/netutils.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/fetchxmlhttpfactory.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/hybrid.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/httpstatus.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/rpc/httpcors.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransport.js","../webchannel-wrapper/dist/temp/src/index.js","../firestore/dist/index.esm2017.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../firestore-compat/src/index.ts","../firestore-compat/src/config.ts","../functions/src/config.ts","../firestore-compat/src/util/input_validation.ts","../firestore-compat/src/api/blob.ts","../firestore-compat/src/api/observer.ts","../firestore-compat/src/api/database.ts","../firestore-compat/src/api/field_path.ts","../firestore-compat/src/api/field_value.ts","../functions/src/serializer.ts","../functions/src/constants.ts","../functions/src/error.ts","../functions/src/context.ts","../functions/src/service.ts","../functions/src/api.ts","../functions/src/index.ts","../functions-compat/src/register.ts","../messaging/src/interfaces/internal-message-payload.ts","../messaging/src/util/constants.ts","../functions-compat/src/service.ts","../functions-compat/src/index.ts","../messaging/src/helpers/array-base64-translator.ts","../messaging/src/helpers/migrate-old-database.ts","../messaging/src/internals/idb-manager.ts","../messaging/src/util/errors.ts","../messaging/src/internals/requests.ts","../messaging/src/internals/token-manager.ts","../messaging/src/helpers/externalizePayload.ts","../messaging/src/helpers/logToFirelog.ts","../messaging/src/helpers/extract-app-config.ts","../messaging/src/messaging-service.ts","../messaging/src/helpers/registerDefaultSw.ts","../messaging/src/api/getToken.ts","../messaging/src/helpers/updateVapidKey.ts","../messaging/src/helpers/updateSwReg.ts","../messaging/src/helpers/logToScion.ts","../messaging/src/listeners/window-listener.ts","../messaging/src/helpers/is-console-message.ts","../messaging/src/helpers/register.ts","../messaging/src/api.ts","../messaging/src/api/deleteToken.ts","../messaging/src/api/onMessage.ts","../messaging/src/listeners/sw-listeners.ts","../messaging/src/helpers/sleep.ts","../messaging/src/api/onBackgroundMessage.ts","../storage/src/implementation/connection.ts","../storage-compat/src/index.ts","../messaging-compat/src/messaging-compat.ts","../messaging-compat/src/registerMessagingCompat.ts","../messaging-compat/src/index.ts","../storage/src/implementation/constants.ts","../storage/src/implementation/error.ts","../storage/src/implementation/location.ts","../storage/src/implementation/failrequest.ts","../storage/src/implementation/type.ts","../storage/src/implementation/url.ts","../storage/src/implementation/utils.ts","../storage/src/implementation/request.ts","../storage/src/implementation/backoff.ts","../storage/src/implementation/fs.ts","../storage/src/platform/browser/base64.ts","../storage/src/implementation/string.ts","../storage/src/implementation/blob.ts","../storage/src/implementation/json.ts","../storage/src/implementation/path.ts","../storage/src/implementation/metadata.ts","../storage/src/implementation/list.ts","../storage/src/implementation/requestinfo.ts","../storage/src/implementation/requests.ts","../storage/src/implementation/taskenums.ts","../storage/src/implementation/observer.ts","../storage/src/implementation/async.ts","../storage/src/platform/browser/connection.ts","../storage/src/task.ts","../storage/src/reference.ts","../storage/src/service.ts","../storage/src/api.ts","../storage/src/index.ts","../storage/src/constants.ts","../storage-compat/src/tasksnapshot.ts","../storage-compat/src/task.ts","../storage-compat/src/list.ts","../storage-compat/src/reference.ts","../storage-compat/src/service.ts","../performance/src/constants.ts","../performance/src/utils/attributes_utils.ts","../performance-compat/src/index.ts","../remote-config-compat/src/index.ts","../performance/src/utils/errors.ts","../performance/src/utils/console_logger.ts","../performance/src/services/api_service.ts","../performance/src/services/iid_service.ts","../performance/src/utils/string_merger.ts","../performance/src/services/settings_service.ts","../performance/src/utils/app_utils.ts","../performance/src/services/remote_config_service.ts","../performance/src/services/initialization_service.ts","../performance/src/services/transport_service.ts","../performance/src/services/perf_logger.ts","../performance/src/utils/metric_utils.ts","../performance/src/resources/trace.ts","../performance/src/resources/network_request.ts","../performance/src/services/oob_resources_service.ts","../performance/src/controllers/perf.ts","../performance/src/index.ts","../performance-compat/src/performance.ts","../remote-config/src/client/remote_config_fetch_client.ts","../remote-config/src/constants.ts","../remote-config/src/errors.ts","../remote-config/src/value.ts","../remote-config/src/api.ts","../remote-config/src/client/caching_client.ts","../remote-config/src/client/rest_client.ts","../remote-config/src/language.ts","../remote-config/src/client/retrying_client.ts","../remote-config/src/remote_config.ts","../remote-config/src/storage/storage.ts","../remote-config/src/storage/storage_cache.ts","../remote-config/src/api2.ts","../remote-config/src/register.ts","../remote-config-compat/src/remoteConfig.ts","compat/index.cdn.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw Error();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n */\nexport const assert = function (assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function (message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy<T>(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\n\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record<string, unknown>)[prop] = deepExtend(\n (target as Record<string, unknown>)[prop],\n (source as Record<string, unknown>)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record<string, string>;\n emulatorHosts?: Record<string, string>;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<R> {\n promise: Promise<R>;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data Javascript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains<T extends object>(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet<T extends object, K extends keyof T>(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map<K extends string, V, U>(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record<string, unknown>)[k];\n const bProp = (b as Record<string, unknown>)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record<string, string> {\n const obj: Record<string, string> = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer<T> {\n // Called once for each value in a stream of values.\n next: NextFn<T>;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver<T> = Partial<Observer<T>>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe<T> {\n (next?: NextFn<T>, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver<T>): Unsubscribe;\n}\n\nexport interface Observable<T> {\n // Subscribe method\n subscribe: Subscribe<T>;\n}\n\nexport type Executor<T> = (observer: Observer<T>) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe<T>(\n executor: Executor<T>,\n onNoObservers?: Executor<T>\n): Subscribe<T> {\n const proxy = new ObserverProxy<T>(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy<T> implements Observer<T> {\n private observers: Array<Observer<T>> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor<T> | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor<T>, onNoObservers?: Executor<T>) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber sychronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn<T> | PartialObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer<T>;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer<T>;\n } else {\n observer = {\n next: nextOrObserver as NextFn<T>,\n error,\n complete\n } as Observer<T>;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn<T>;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer<T>);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer<T>) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer<T>) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function (\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid context object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Copied from https://stackoverflow.com/a/2117523\n * Generates a new uuid.\n * @public\n */\nexport const uuidv4 = function (): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0,\n v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider<T extends Name> {\n private component: Component<T> | null = null;\n private readonly instances: Map<string, NameServiceMapping[T]> = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred<NameServiceMapping[T]>\n > = new Map();\n private readonly instancesOptions: Map<string, Record<string, unknown>> =\n new Map();\n private onInitCallbacks: Map<string, Set<OnInitCallBack<T>>> = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier?: string): Promise<NameServiceMapping[T]> {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred<NameServiceMapping[T]>();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n\n getComponent(): Component<T> | null {\n return this.component;\n }\n\n setComponent(component: Component<T>): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n })!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise<void> {\n const services = Array.from(this.instances.values());\n\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record<string, unknown> {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack<T>, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set<OnInitCallBack<T>>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record<string, unknown>;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n\n private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\n );\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager<T extends Name>(component: Component<T>): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map<string, Provider<Name>>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider<T extends Name>(name: T): Provider<T> {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider<T>;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider<T>(name, this);\n this.providers.set(name, provider as unknown as Provider<Name>);\n\n return provider as Provider<T>;\n }\n\n getProviders(): Array<Provider<Name>> {\n return Array.from(this.providers.values());\n }\n}\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate() as VersionService;\n return `${service.library}/${service.version}`;\n } else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider: Provider<Name>): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map<string, FirebaseApp>();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map<string, Component<any>>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent<T extends Name>(\n app: FirebaseApp,\n component: Component<T>\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent<T extends Name>(\n component: Component<T>\n): boolean {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n return true;\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nexport function _getProvider<T extends Name>(\n app: FirebaseApp,\n name: T\n): Provider<T> {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nexport function _removeServiceInstance<T extends Name>(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete'\n}\n\nconst ERRORS: ErrorMap<AppError> = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call Firebase App.initializeApp()',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppError, ErrorParams>(\n 'app',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n private readonly _options: FirebaseOptions;\n private readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required<FirebaseAppSettings>;\n private _automaticDataCollectionEnabled: boolean;\n private _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required<FirebaseAppSettings>,\n container: ComponentContainer\n ) {\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n this.checkDestroyed();\n return this._name;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed();\n return this._options;\n }\n\n get config(): Required<FirebaseAppSettings> {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\n }\n\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n private checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this._name });\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { _apps, _components, _registerComponent } from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport { deepEqual, getDefaultAppConfig } from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://<OTHER_DATABASE_NAME>.firebaseio.com\",\n * storageBucket: \"<OTHER_STORAGE_BUCKET>.appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required<FirebaseAppSettings> = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: false,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\n\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nexport async function deleteApp(app: FirebaseApp): Promise<void> {\n const name = app.name;\n if (_apps.has(name)) {\n _apps.delete(name);\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\n}\n\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nexport function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n): void {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n}\n\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\n\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<AppDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<AppDB>> {\n if (!dbPromise) {\n dbPromise = openDB<AppDB>(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(STORE_NAME);\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise<HeartbeatsInIndexedDB | undefined> {\n try {\n const db = await getDbPromise();\n return db\n .transaction(STORE_NAME)\n .objectStore(STORE_NAME)\n .get(computeKey(app)) as Promise<HeartbeatsInIndexedDB | undefined>;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise<void> {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n return tx.done;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\n\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (hearbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise<HeartbeatsInIndexedDB>;\n constructor(private readonly container: ComponentContainer) {\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat(): Promise<void> {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache === null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n }\n // Remove entries older than 30 days.\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(\n singleDateHeartbeat => {\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n const now = Date.now();\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n }\n );\n return this._storage.overwrite(this._heartbeatsCache);\n }\n\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader(): Promise<string> {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (\n this._heartbeatsCache === null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n } else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n }\n}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(\n hb => hb.agent === singleDateHeartbeat.agent\n );\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n } else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise<boolean>;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise<HeartbeatsInIndexedDB> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n return idbHeartbeatObject || { heartbeats: [] };\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\n}\n","/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseOptions } from './public-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstantiationMode,\n Name\n} from '@firebase/component';\nimport {\n deleteApp,\n _addComponent,\n _addOrOverwriteComponent,\n _DEFAULT_ENTRY_NAME,\n _FirebaseAppInternal as _FirebaseAppExp\n} from '@firebase/app';\nimport { _FirebaseService, _FirebaseNamespace } from './types';\nimport { Compat } from '@firebase/util';\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface _FirebaseApp {\n /**\n * The (read-only) name (identifier) for this App. '[DEFAULT]' is the default\n * App.\n */\n name: string;\n\n /**\n * The (read-only) configuration options from the app initialization.\n */\n options: FirebaseOptions;\n\n /**\n * The settable config flag for GDPR opt-in/opt-out\n */\n automaticDataCollectionEnabled: boolean;\n\n /**\n * Make the given App unusable and free resources.\n */\n delete(): Promise<void>;\n}\n/**\n * Global context object for a collection of services using\n * a shared authentication state.\n *\n * marked as internal because it references internal types exported from @firebase/app\n * @internal\n */\nexport class FirebaseAppImpl implements Compat<_FirebaseAppExp>, _FirebaseApp {\n private container: ComponentContainer;\n\n constructor(\n readonly _delegate: _FirebaseAppExp,\n private readonly firebase: _FirebaseNamespace\n ) {\n // add itself to container\n _addComponent(\n _delegate,\n new Component('app-compat', () => this, ComponentType.PUBLIC)\n );\n\n this.container = _delegate.container;\n }\n\n get automaticDataCollectionEnabled(): boolean {\n return this._delegate.automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val) {\n this._delegate.automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n return this._delegate.name;\n }\n\n get options(): FirebaseOptions {\n return this._delegate.options;\n }\n\n delete(): Promise<void> {\n return new Promise<void>(resolve => {\n this._delegate.checkDestroyed();\n resolve();\n }).then(() => {\n this.firebase.INTERNAL.removeApp(this.name);\n return deleteApp(this._delegate);\n });\n }\n\n /**\n * Return a service instance associated with this app (creating it\n * on demand), identified by the passed instanceIdentifier.\n *\n * NOTE: Currently storage and functions are the only ones that are leveraging this\n * functionality. They invoke it by calling:\n *\n * ```javascript\n * firebase.app().storage('STORAGE BUCKET ID')\n * ```\n *\n * The service name is passed to this already\n * @internal\n */\n _getService(\n name: string,\n instanceIdentifier: string = _DEFAULT_ENTRY_NAME\n ): _FirebaseService {\n this._delegate.checkDestroyed();\n\n // Initialize instance if InstatiationMode is `EXPLICIT`.\n const provider = this._delegate.container.getProvider(name as Name);\n if (\n !provider.isInitialized() &&\n provider.getComponent()?.instantiationMode === InstantiationMode.EXPLICIT\n ) {\n provider.initialize();\n }\n\n // getImmediate will always succeed because _getService is only called for registered components.\n return provider.getImmediate({\n identifier: instanceIdentifier\n }) as unknown as _FirebaseService;\n }\n\n /**\n * Remove a service instance from the cache, so we will create a new instance for this service\n * when people try to get it again.\n *\n * NOTE: currently only firestore uses this functionality to support firestore shutdown.\n *\n * @param name The service name\n * @param instanceIdentifier instance identifier in case multiple instances are allowed\n * @internal\n */\n _removeServiceInstance(\n name: string,\n instanceIdentifier: string = _DEFAULT_ENTRY_NAME\n ): void {\n this._delegate.container\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .getProvider(name as any)\n .clearInstance(instanceIdentifier);\n }\n\n /**\n * @param component the component being added to this app's container\n * @internal\n */\n _addComponent(component: Component): void {\n _addComponent(this._delegate, component);\n }\n\n _addOrOverwriteComponent(component: Component): void {\n _addOrOverwriteComponent(this._delegate, component);\n }\n\n toJSON(): object {\n return {\n name: this.name,\n automaticDataCollectionEnabled: this.automaticDataCollectionEnabled,\n options: this.options\n };\n }\n}\n\n// TODO: investigate why the following needs to be commented out\n// Prevent dead-code elimination of these methods w/o invalid property\n// copying.\n// (FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) ||\n// FirebaseAppImpl.prototype.delete ||\n// console.log('dc');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n INVALID_APP_ARGUMENT = 'invalid-app-argument'\n}\n\nconst ERRORS: ErrorMap<AppError> = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call Firebase App.initializeApp()',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.'\n};\n\ntype ErrorParams = { [key in AppError]: { appName: string } };\n\nexport const ERROR_FACTORY = new ErrorFactory<AppError, ErrorParams>(\n 'app-compat',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, FirebaseOptions } from './public-types';\nimport {\n _FirebaseNamespace,\n _FirebaseService,\n FirebaseServiceNamespace\n} from './types';\nimport * as modularAPIs from '@firebase/app';\nimport { _FirebaseAppInternal as _FirebaseAppExp } from '@firebase/app';\nimport { Component, ComponentType, Name } from '@firebase/component';\n\nimport { deepExtend, contains } from '@firebase/util';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport { FirebaseAppLiteImpl } from './lite/firebaseAppLite';\n\n/**\n * Because auth can't share code with other components, we attach the utility functions\n * in an internal namespace to share code.\n * This function return a firebase namespace object without\n * any utility functions, so it can be shared between the regular firebaseNamespace and\n * the lite version.\n */\nexport function createFirebaseNamespaceCore(\n firebaseAppImpl: typeof FirebaseAppImpl | typeof FirebaseAppLiteImpl\n): _FirebaseNamespace {\n const apps: { [name: string]: FirebaseApp } = {};\n // // eslint-disable-next-line @typescript-eslint/no-explicit-any\n // const components = new Map<string, Component<any>>();\n\n // A namespace is a plain JavaScript Object.\n const namespace: _FirebaseNamespace = {\n // Hack to prevent Babel from modifying the object returned\n // as the firebase namespace.\n // @ts-ignore\n __esModule: true,\n initializeApp: initializeAppCompat,\n // @ts-ignore\n app,\n registerVersion: modularAPIs.registerVersion,\n setLogLevel: modularAPIs.setLogLevel,\n onLog: modularAPIs.onLog,\n // @ts-ignore\n apps: null,\n SDK_VERSION: modularAPIs.SDK_VERSION,\n INTERNAL: {\n registerComponent: registerComponentCompat,\n removeApp,\n useAsService,\n modularAPIs\n }\n };\n\n // Inject a circular default export to allow Babel users who were previously\n // using:\n //\n // import firebase from 'firebase';\n // which becomes: var firebase = require('firebase').default;\n //\n // instead of\n //\n // import * as firebase from 'firebase';\n // which becomes: var firebase = require('firebase');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)['default'] = namespace;\n\n // firebase.apps is a read-only getter.\n Object.defineProperty(namespace, 'apps', {\n get: getApps\n });\n\n /**\n * Called by App.delete() - but before any services associated with the App\n * are deleted.\n */\n function removeApp(name: string): void {\n delete apps[name];\n }\n\n /**\n * Get the App object for a given name (or DEFAULT).\n */\n function app(name?: string): FirebaseApp {\n name = name || modularAPIs._DEFAULT_ENTRY_NAME;\n if (!contains(apps, name)) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n return apps[name];\n }\n\n // @ts-ignore\n app['App'] = firebaseAppImpl;\n\n /**\n * Create a new App instance (name must be unique).\n *\n * This function is idempotent. It can be called more than once and return the same instance using the same options and config.\n */\n function initializeAppCompat(\n options: FirebaseOptions,\n rawConfig = {}\n ): FirebaseApp {\n const app = modularAPIs.initializeApp(\n options,\n rawConfig\n ) as _FirebaseAppExp;\n\n if (contains(apps, app.name)) {\n return apps[app.name];\n }\n\n const appCompat = new firebaseAppImpl(app, namespace);\n apps[app.name] = appCompat;\n return appCompat;\n }\n\n /*\n * Return an array of all the non-deleted FirebaseApps.\n */\n function getApps(): FirebaseApp[] {\n // Make a copy so caller cannot mutate the apps list.\n return Object.keys(apps).map(name => apps[name]);\n }\n\n function registerComponentCompat<T extends Name>(\n component: Component<T>\n ): FirebaseServiceNamespace<_FirebaseService> | null {\n const componentName = component.name;\n const componentNameWithoutCompat = componentName.replace('-compat', '');\n if (\n modularAPIs._registerComponent(component) &&\n component.type === ComponentType.PUBLIC\n ) {\n // create service namespace for public components\n // The Service namespace is an accessor function ...\n const serviceNamespace = (\n appArg: FirebaseApp = app()\n ): _FirebaseService => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof (appArg as any)[componentNameWithoutCompat] !== 'function') {\n // Invalid argument.\n // This happens in the following case: firebase.storage('gs:/')\n throw ERROR_FACTORY.create(AppError.INVALID_APP_ARGUMENT, {\n appName: componentName\n });\n }\n\n // Forward service instance lookup to the FirebaseApp.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (appArg as any)[componentNameWithoutCompat]();\n };\n\n // ... and a container for service-level properties.\n if (component.serviceProps !== undefined) {\n deepExtend(serviceNamespace, component.serviceProps);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)[componentNameWithoutCompat] = serviceNamespace;\n\n // Patch the FirebaseAppImpl prototype\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (firebaseAppImpl.prototype as any)[componentNameWithoutCompat] =\n // TODO: The eslint disable can be removed and the 'ignoreRestArgs'\n // option added to the no-explicit-any rule when ESlint releases it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function (...args: any) {\n const serviceFxn = this._getService.bind(this, componentName);\n return serviceFxn.apply(\n this,\n component.multipleInstances ? args : []\n );\n };\n }\n\n return component.type === ComponentType.PUBLIC\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)[componentNameWithoutCompat]\n : null;\n }\n\n // Map the requested service to a registered service name\n // (used to map auth to serverAuth service when needed).\n function useAsService(app: FirebaseApp, name: string): string | null {\n if (name === 'serverAuth') {\n return null;\n }\n\n const useService = name;\n\n return useService;\n }\n\n return namespace;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseNamespace } from './public-types';\nimport { createSubscribe, deepExtend, ErrorFactory } from '@firebase/util';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { createFirebaseNamespaceCore } from './firebaseNamespaceCore';\n\n/**\n * Return a firebase namespace object.\n *\n * In production, this will be called exactly once and the result\n * assigned to the 'firebase' global. It may be called multiple times\n * in unit tests.\n */\nexport function createFirebaseNamespace(): FirebaseNamespace {\n const namespace = createFirebaseNamespaceCore(FirebaseAppImpl);\n namespace.INTERNAL = {\n ...namespace.INTERNAL,\n createFirebaseNamespace,\n extendNamespace,\n createSubscribe,\n ErrorFactory,\n deepExtend\n };\n\n /**\n * Patch the top-level firebase namespace with additional properties.\n *\n * firebase.INTERNAL.extendNamespace()\n */\n function extendNamespace(props: { [prop: string]: unknown }): void {\n deepExtend(namespace, props);\n }\n\n return namespace;\n}\n\nexport const firebase = createFirebaseNamespace();\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-compat');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseNamespace } from './public-types';\nimport { isBrowser } from '@firebase/util';\nimport { firebase as firebaseNamespace } from './firebaseNamespace';\nimport { logger } from './logger';\nimport { registerCoreComponents } from './registerCoreComponents';\n\n// Firebase Lite detection\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nif (isBrowser() && (self as any).firebase !== undefined) {\n logger.warn(`\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n `);\n\n // eslint-disable-next-line\n const sdkVersion = ((self as any).firebase as FirebaseNamespace).SDK_VERSION;\n if (sdkVersion && sdkVersion.indexOf('LITE') >= 0) {\n logger.warn(`\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n `);\n }\n}\n\nconst firebase = firebaseNamespace;\n\nregisterCoreComponents();\n\n// eslint-disable-next-line import/no-default-export\nexport default firebase;\n\nexport { _FirebaseNamespace, _FirebaseService } from './types';\nexport { FirebaseApp, FirebaseNamespace } from './public-types';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion } from '@firebase/app';\n\nimport { name, version } from '../package.json';\n\nexport function registerCoreComponents(variant?: string): void {\n // Register `app` package.\n registerVersion(name, version, variant);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase from '@firebase/app-compat';\nimport { name, version } from '../../package.json';\n\nfirebase.registerVersion(name, version, 'app-compat');\n\nexport default firebase;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { version } from '../../package.json';\n\nexport const PENDING_TIMEOUT_MS = 10000;\n\nexport const PACKAGE_VERSION = `w:${version}`;\nexport const INTERNAL_AUTH_VERSION = 'FIS_v2';\n\nexport const INSTALLATIONS_API_URL =\n 'https://firebaseinstallations.googleapis.com/v1';\n\nexport const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\n\nexport const SERVICE = 'installations';\nexport const SERVICE_NAME = 'Installations';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n NOT_REGISTERED = 'not-registered',\n INSTALLATION_NOT_FOUND = 'installation-not-found',\n REQUEST_FAILED = 'request-failed',\n APP_OFFLINE = 'app-offline',\n DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n [ErrorCode.REQUEST_FAILED]:\n '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n [ErrorCode.DELETE_PENDING_REGISTRATION]:\n \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.REQUEST_FAILED]: {\n requestName: string;\n [index: string]: string | number; // to make Typescript 3.8 happy\n } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n serverCode: number;\n serverMessage: string;\n serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & { customData: ServerErrorData };\n\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\nexport function isServerError(error: unknown): error is ServerError {\n return (\n error instanceof FirebaseError &&\n error.code.includes(ErrorCode.REQUEST_FAILED)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport {\n INSTALLATIONS_API_URL,\n INTERNAL_AUTH_VERSION\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { AppConfig } from '../interfaces/installation-impl';\n\nexport function getInstallationsEndpoint({ projectId }: AppConfig): string {\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\n}\n\nexport function extractAuthTokenInfoFromResponse(\n response: GenerateAuthTokenResponse\n): CompletedAuthToken {\n return {\n token: response.token,\n requestStatus: RequestStatus.COMPLETED,\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\n creationTime: Date.now()\n };\n}\n\nexport async function getErrorFromResponse(\n requestName: string,\n response: Response\n): Promise<FirebaseError> {\n const responseJson: ErrorResponse = await response.json();\n const errorData = responseJson.error;\n return ERROR_FACTORY.create(ErrorCode.REQUEST_FAILED, {\n requestName,\n serverCode: errorData.code,\n serverMessage: errorData.message,\n serverStatus: errorData.status\n });\n}\n\nexport function getHeaders({ apiKey }: AppConfig): Headers {\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\nexport function getHeadersWithAuth(\n appConfig: AppConfig,\n { refreshToken }: RegisteredInstallationEntry\n): Headers {\n const headers = getHeaders(appConfig);\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\n return headers;\n}\n\nexport interface ErrorResponse {\n error: {\n code: number;\n message: string;\n status: string;\n };\n}\n\n/**\n * Calls the passed in fetch wrapper and returns the response.\n * If the returned response has a status of 5xx, re-runs the function once and\n * returns the response.\n */\nexport async function retryIfServerError(\n fn: () => Promise<Response>\n): Promise<Response> {\n const result = await fn();\n\n if (result.status >= 500 && result.status < 600) {\n // Internal Server Error. Retry request.\n return fn();\n }\n\n return result;\n}\n\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn: string): number {\n // This works because the server will never respond with fractions of a second.\n return Number(responseExpiresIn.replace('s', '000'));\n}\n\nfunction getAuthorizationHeader(refreshToken: string): string {\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bufferToBase64UrlSafe } from './buffer-to-base64-url-safe';\n\nexport const VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\nexport const INVALID_FID = '';\n\n/**\n * Generates a new FID using random values from Web Crypto API.\n * Returns an empty string if FID generation fails for any reason.\n */\nexport function generateFid(): string {\n try {\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\n // bytes. our implementation generates a 17 byte array instead.\n const fidByteArray = new Uint8Array(17);\n const crypto =\n self.crypto || (self as unknown as { msCrypto: Crypto }).msCrypto;\n crypto.getRandomValues(fidByteArray);\n\n // Replace the first 4 random bits with the constant FID header of 0b0111.\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\n\n const fid = encode(fidByteArray);\n\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\n } catch {\n // FID generation errored\n return INVALID_FID;\n }\n}\n\n/** Converts a FID Uint8Array to a base64 string representation. */\nfunction encode(fidByteArray: Uint8Array): string {\n const b64String = bufferToBase64UrlSafe(fidByteArray);\n\n // Remove the 23rd character that was added because of the extra 4 bits at the\n // end of our 17 byte array, and the '=' padding.\n return b64String.substr(0, 22);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function bufferToBase64UrlSafe(array: Uint8Array): string {\n const b64 = btoa(String.fromCharCode(...array));\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '../interfaces/installation-impl';\n\n/** Returns a string key that can be used to identify the app. */\nexport function getKey(appConfig: AppConfig): string {\n return `${appConfig.appName}!${appConfig.appId}`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { IdChangeCallbackFn } from '../api';\n\nconst fidChangeCallbacks: Map<string, Set<IdChangeCallbackFn>> = new Map();\n\n/**\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\n * change to other tabs.\n */\nexport function fidChanged(appConfig: AppConfig, fid: string): void {\n const key = getKey(appConfig);\n\n callFidChangeCallbacks(key, fid);\n broadcastFidChange(key, fid);\n}\n\nexport function addCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n // Open the broadcast channel if it's not already open,\n // to be able to listen to change events from other tabs.\n getBroadcastChannel();\n\n const key = getKey(appConfig);\n\n let callbackSet = fidChangeCallbacks.get(key);\n if (!callbackSet) {\n callbackSet = new Set();\n fidChangeCallbacks.set(key, callbackSet);\n }\n callbackSet.add(callback);\n}\n\nexport function removeCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n const key = getKey(appConfig);\n\n const callbackSet = fidChangeCallbacks.get(key);\n\n if (!callbackSet) {\n return;\n }\n\n callbackSet.delete(callback);\n if (callbackSet.size === 0) {\n fidChangeCallbacks.delete(key);\n }\n\n // Close broadcast channel if there are no more callbacks.\n closeBroadcastChannel();\n}\n\nfunction callFidChangeCallbacks(key: string, fid: string): void {\n const callbacks = fidChangeCallbacks.get(key);\n if (!callbacks) {\n return;\n }\n\n for (const callback of callbacks) {\n callback(fid);\n }\n}\n\nfunction broadcastFidChange(key: string, fid: string): void {\n const channel = getBroadcastChannel();\n if (channel) {\n channel.postMessage({ key, fid });\n }\n closeBroadcastChannel();\n}\n\nlet broadcastChannel: BroadcastChannel | null = null;\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\nfunction getBroadcastChannel(): BroadcastChannel | null {\n if (!broadcastChannel && 'BroadcastChannel' in self) {\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\n broadcastChannel.onmessage = e => {\n callFidChangeCallbacks(e.data.key, e.data.fid);\n };\n }\n return broadcastChannel;\n}\n\nfunction closeBroadcastChannel(): void {\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\n broadcastChannel.close();\n broadcastChannel = null;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DBSchema, IDBPDatabase, openDB } from 'idb';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { InstallationEntry } from '../interfaces/installation-entry';\nimport { getKey } from '../util/get-key';\nimport { fidChanged } from './fid-changed';\n\nconst DATABASE_NAME = 'firebase-installations-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\n\ninterface InstallationsDB extends DBSchema {\n 'firebase-installations-store': {\n key: string;\n value: InstallationEntry | undefined;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<InstallationsDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<InstallationsDB>> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n db.createObjectStore(OBJECT_STORE_NAME);\n }\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function get(\n appConfig: AppConfig\n): Promise<InstallationEntry | undefined> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n return db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key) as Promise<InstallationEntry>;\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function set<ValueType extends InstallationEntry>(\n appConfig: AppConfig,\n value: ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue = (await objectStore.get(key)) as InstallationEntry;\n await objectStore.put(value, key);\n await tx.done;\n\n if (!oldValue || oldValue.fid !== value.fid) {\n fidChanged(appConfig, value.fid);\n }\n\n return value;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function remove(appConfig: AppConfig): Promise<void> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.done;\n}\n\n/**\n * Atomically updates a record with the result of updateFn, which gets\n * called with the current value. If newValue is undefined, the record is\n * deleted instead.\n * @return Updated value\n */\nexport async function update<ValueType extends InstallationEntry | undefined>(\n appConfig: AppConfig,\n updateFn: (previousValue: InstallationEntry | undefined) => ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const store = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue: InstallationEntry | undefined = (await store.get(\n key\n )) as InstallationEntry;\n const newValue = updateFn(oldValue);\n\n if (newValue === undefined) {\n await store.delete(key);\n } else {\n await store.put(newValue, key);\n }\n await tx.done;\n\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\n fidChanged(appConfig, newValue.fid);\n }\n\n return newValue;\n}\n\nexport async function clear(): Promise<void> {\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).clear();\n await tx.done;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createInstallationRequest } from '../functions/create-installation-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n InProgressInstallationEntry,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { generateFid, INVALID_FID } from './generate-fid';\nimport { remove, set, update } from './idb-manager';\n\nexport interface InstallationEntryWithRegistrationPromise {\n installationEntry: InstallationEntry;\n /** Exist iff the installationEntry is not registered. */\n registrationPromise?: Promise<RegisteredInstallationEntry>;\n}\n\n/**\n * Updates and returns the InstallationEntry from the database.\n * Also triggers a registration request if it is necessary and possible.\n */\nexport async function getInstallationEntry(\n installations: FirebaseInstallationsImpl\n): Promise<InstallationEntryWithRegistrationPromise> {\n let registrationPromise: Promise<RegisteredInstallationEntry> | undefined;\n\n const installationEntry = await update(installations.appConfig, oldEntry => {\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n const entryWithPromise = triggerRegistrationIfNecessary(\n installations,\n installationEntry\n );\n registrationPromise = entryWithPromise.registrationPromise;\n return entryWithPromise.installationEntry;\n });\n\n if (installationEntry.fid === INVALID_FID) {\n // FID generation failed. Waiting for the FID from the server.\n return { installationEntry: await registrationPromise! };\n }\n\n return {\n installationEntry,\n registrationPromise\n };\n}\n\n/**\n * Creates a new Installation Entry if one does not exist.\n * Also clears timed out pending requests.\n */\nfunction updateOrCreateInstallationEntry(\n oldEntry: InstallationEntry | undefined\n): InstallationEntry {\n const entry: InstallationEntry = oldEntry || {\n fid: generateFid(),\n registrationStatus: RequestStatus.NOT_STARTED\n };\n\n return clearTimedOutRequest(entry);\n}\n\n/**\n * If the Firebase Installation is not registered yet, this will trigger the\n * registration and return an InProgressInstallationEntry.\n *\n * If registrationPromise does not exist, the installationEntry is guaranteed\n * to be registered.\n */\nfunction triggerRegistrationIfNecessary(\n installations: FirebaseInstallationsImpl,\n installationEntry: InstallationEntry\n): InstallationEntryWithRegistrationPromise {\n if (installationEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n if (!navigator.onLine) {\n // Registration required but app is offline.\n const registrationPromiseWithError = Promise.reject(\n ERROR_FACTORY.create(ErrorCode.APP_OFFLINE)\n );\n return {\n installationEntry,\n registrationPromise: registrationPromiseWithError\n };\n }\n\n // Try registering. Change status to IN_PROGRESS.\n const inProgressEntry: InProgressInstallationEntry = {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.IN_PROGRESS,\n registrationTime: Date.now()\n };\n const registrationPromise = registerInstallation(\n installations,\n inProgressEntry\n );\n return { installationEntry: inProgressEntry, registrationPromise };\n } else if (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS\n ) {\n return {\n installationEntry,\n registrationPromise: waitUntilFidRegistration(installations)\n };\n } else {\n return { installationEntry };\n }\n}\n\n/** This will be executed only once for each new Firebase Installation. */\nasync function registerInstallation(\n installations: FirebaseInstallationsImpl,\n installationEntry: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n try {\n const registeredInstallationEntry = await createInstallationRequest(\n installations,\n installationEntry\n );\n return set(installations.appConfig, registeredInstallationEntry);\n } catch (e) {\n if (isServerError(e) && e.customData.serverCode === 409) {\n // Server returned a \"FID can not be used\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n // Registration failed. Set FID as not registered.\n await set(installations.appConfig, {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n });\n }\n throw e;\n }\n}\n\n/** Call if FID registration is pending in another request. */\nasync function waitUntilFidRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<RegisteredInstallationEntry> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry: InstallationEntry = await updateInstallationRequest(\n installations.appConfig\n );\n while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // createInstallation request still in progress.\n await sleep(100);\n\n entry = await updateInstallationRequest(installations.appConfig);\n }\n\n if (entry.registrationStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n const { installationEntry, registrationPromise } =\n await getInstallationEntry(installations);\n\n if (registrationPromise) {\n return registrationPromise;\n } else {\n // if there is no registrationPromise, entry is registered.\n return installationEntry as RegisteredInstallationEntry;\n }\n }\n\n return entry;\n}\n\n/**\n * Called only if there is a CreateInstallation request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * CreateInstallation request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateInstallationRequest(\n appConfig: AppConfig\n): Promise<InstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!oldEntry) {\n throw ERROR_FACTORY.create(ErrorCode.INSTALLATION_NOT_FOUND);\n }\n return clearTimedOutRequest(oldEntry);\n });\n}\n\nfunction clearTimedOutRequest(entry: InstallationEntry): InstallationEntry {\n if (hasInstallationRequestTimedOut(entry)) {\n return {\n fid: entry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n };\n }\n\n return entry;\n}\n\nfunction hasInstallationRequestTimedOut(\n installationEntry: InstallationEntry\n): boolean {\n return (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS &&\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CreateInstallationResponse } from '../interfaces/api-response';\nimport {\n InProgressInstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { INTERNAL_AUTH_VERSION, PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeaders,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\n\nexport async function createInstallationRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n { fid }: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n const endpoint = getInstallationsEndpoint(appConfig);\n\n const headers = getHeaders(appConfig);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n fid,\n authVersion: INTERNAL_AUTH_VERSION,\n appId: appConfig.appId,\n sdkVersion: PACKAGE_VERSION\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: CreateInstallationResponse = await response.json();\n const registeredInstallationEntry: RegisteredInstallationEntry = {\n fid: responseValue.fid || fid,\n registrationStatus: RequestStatus.COMPLETED,\n refreshToken: responseValue.refreshToken,\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\n };\n return registeredInstallationEntry;\n } else {\n throw await getErrorFromResponse('Create Installation', response);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry\n} from '../interfaces/installation-entry';\nimport { PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\nimport {\n FirebaseInstallationsImpl,\n AppConfig\n} from '../interfaces/installation-impl';\n\nexport async function generateAuthTokenRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n installation: {\n sdkVersion: PACKAGE_VERSION,\n appId: appConfig.appId\n }\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: GenerateAuthTokenResponse = await response.json();\n const completedAuthToken: CompletedAuthToken =\n extractAuthTokenInfoFromResponse(responseValue);\n return completedAuthToken;\n } else {\n throw await getErrorFromResponse('Generate Auth Token', response);\n }\n}\n\nfunction getGenerateAuthTokenEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { generateAuthTokenRequest } from '../functions/generate-auth-token-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n AuthToken,\n CompletedAuthToken,\n InProgressAuthToken,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { remove, set, update } from './idb-manager';\n\n/**\n * Returns a valid authentication token for the installation. Generates a new\n * token if one doesn't exist, is expired or about to expire.\n *\n * Should only be called if the Firebase Installation is registered.\n */\nexport async function refreshAuthToken(\n installations: FirebaseInstallationsImpl,\n forceRefresh = false\n): Promise<CompletedAuthToken> {\n let tokenPromise: Promise<CompletedAuthToken> | undefined;\n const entry = await update(installations.appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\n // There is a valid token in the DB.\n return oldEntry;\n } else if (oldAuthToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // There already is a token request in progress.\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\n return oldEntry;\n } else {\n // No token or token expired.\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n }\n\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\n return inProgressEntry;\n }\n });\n\n const authToken = tokenPromise\n ? await tokenPromise\n : (entry.authToken as CompletedAuthToken);\n return authToken;\n}\n\n/**\n * Call only if FID is registered and Auth Token request is in progress.\n *\n * Waits until the current pending request finishes. If the request times out,\n * tries once in this thread as well.\n */\nasync function waitUntilAuthTokenRequest(\n installations: FirebaseInstallationsImpl,\n forceRefresh: boolean\n): Promise<CompletedAuthToken> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry = await updateAuthTokenRequest(installations.appConfig);\n while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // generateAuthToken still in progress.\n await sleep(100);\n\n entry = await updateAuthTokenRequest(installations.appConfig);\n }\n\n const authToken = entry.authToken;\n if (authToken.requestStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n return refreshAuthToken(installations, forceRefresh);\n } else {\n return authToken;\n }\n}\n\n/**\n * Called only if there is a GenerateAuthToken request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * GenerateAuthToken request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateAuthTokenRequest(\n appConfig: AppConfig\n): Promise<RegisteredInstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\n return {\n ...oldEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n }\n\n return oldEntry;\n });\n}\n\nasync function fetchAuthTokenFromServer(\n installations: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n try {\n const authToken = await generateAuthTokenRequest(\n installations,\n installationEntry\n );\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken\n };\n await set(installations.appConfig, updatedInstallationEntry);\n return authToken;\n } catch (e) {\n if (\n isServerError(e) &&\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)\n ) {\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n await set(installations.appConfig, updatedInstallationEntry);\n }\n throw e;\n }\n}\n\nfunction isEntryRegistered(\n installationEntry: InstallationEntry | undefined\n): installationEntry is RegisteredInstallationEntry {\n return (\n installationEntry !== undefined &&\n installationEntry.registrationStatus === RequestStatus.COMPLETED\n );\n}\n\nfunction isAuthTokenValid(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.COMPLETED &&\n !isAuthTokenExpired(authToken)\n );\n}\n\nfunction isAuthTokenExpired(authToken: CompletedAuthToken): boolean {\n const now = Date.now();\n return (\n now < authToken.creationTime ||\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER\n );\n}\n\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\nfunction makeAuthTokenRequestInProgressEntry(\n oldEntry: RegisteredInstallationEntry\n): RegisteredInstallationEntry {\n const inProgressAuthToken: InProgressAuthToken = {\n requestStatus: RequestStatus.IN_PROGRESS,\n requestTime: Date.now()\n };\n return {\n ...oldEntry,\n authToken: inProgressAuthToken\n };\n}\n\nfunction hasAuthTokenRequestTimedOut(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.IN_PROGRESS &&\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns a Firebase Installations auth token, identifying the current\n * Firebase Installation.\n * @param installations - The `Installations` instance.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getToken(\n installations: Installations,\n forceRefresh = false\n): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n await completeInstallationRegistration(installationsImpl);\n\n // At this point we either have a Registered Installation in the DB, or we've\n // already thrown an error.\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\n return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<void> {\n const { registrationPromise } = await getInstallationEntry(installations);\n\n if (registrationPromise) {\n // A createInstallation request is in progress. Wait until it finishes.\n await registrationPromise;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: Array<keyof FirebaseOptions> = [\n 'projectId',\n 'apiKey',\n 'appId'\n ];\n\n for (const keyName of configKeys) {\n if (!app.options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: app.options.projectId!,\n apiKey: app.options.apiKey!,\n appId: app.options.appId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, _getProvider } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer\n} from '@firebase/component';\nimport { getId, getToken } from '../api/index';\nimport { _FirebaseInstallationsInternal } from '../interfaces/public-types';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { extractAppConfig } from '../helpers/extract-app-config';\n\nconst INSTALLATIONS_NAME = 'installations';\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\n\nconst publicFactory: InstanceFactory<'installations'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Throws if app isn't configured properly.\n const appConfig = extractAppConfig(app);\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n\n const installationsImpl: FirebaseInstallationsImpl = {\n app,\n appConfig,\n heartbeatServiceProvider,\n _delete: () => Promise.resolve()\n };\n return installationsImpl;\n};\n\nconst internalFactory: InstanceFactory<'installations-internal'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Internal FIS instance relies on public FIS instance.\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\n\n const installationsInternal: _FirebaseInstallationsInternal = {\n getId: () => getId(installations),\n getToken: (forceRefresh?: boolean) => getToken(installations, forceRefresh)\n };\n return installationsInternal;\n};\n\nexport function registerInstallations(): void {\n _registerComponent(\n new Component(INSTALLATIONS_NAME, publicFactory, ComponentType.PUBLIC)\n );\n _registerComponent(\n new Component(\n INSTALLATIONS_NAME_INTERNAL,\n internalFactory,\n ComponentType.PRIVATE\n )\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Creates a Firebase Installation if there isn't one for the app and\n * returns the Installation ID.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function getId(installations: Installations): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n const { installationEntry, registrationPromise } = await getInstallationEntry(\n installationsImpl\n );\n\n if (registrationPromise) {\n registrationPromise.catch(console.error);\n } else {\n // If the installation is already registered, update the authentication\n // token if needed.\n refreshAuthToken(installationsImpl).catch(console.error);\n }\n\n return installationEntry.fid;\n}\n","/**\n * Firebase Installations\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerInstallations } from './functions/config';\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nexport * from './api';\nexport * from './interfaces/public-types';\n\nregisterInstallations();\nregisterVersion(name, version);\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\nregisterVersion(name, version, '__BUILD_TARGET__');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Analytics.\n */\nexport const ANALYTICS_TYPE = 'analytics';\n\n// Key to attach FID to in gtag params.\nexport const GA_FID_KEY = 'firebase_id';\nexport const ORIGIN_KEY = 'origin';\n\nexport const FETCH_TIMEOUT_MILLIS = 60 * 1000;\n\nexport const DYNAMIC_CONFIG_URL =\n 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';\n\nexport const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';\n\nexport const enum GtagCommand {\n EVENT = 'event',\n SET = 'set',\n CONFIG = 'config',\n CONSENT = 'consent'\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/analytics');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { DynamicConfig, DataLayer, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GTAG_URL } from './constants';\nimport { logger } from './logger';\n\n// Possible parameter types for gtag 'event' and 'config' commands\ntype GtagConfigOrEventParams = ControlParams & EventParams & CustomParams;\n\n/**\n * Makeshift polyfill for Promise.allSettled(). Resolves when all promises\n * have either resolved or rejected.\n *\n * @param promises Array of promises to wait for.\n */\nexport function promiseAllSettled<T>(\n promises: Array<Promise<T>>\n): Promise<T[]> {\n return Promise.all(promises.map(promise => promise.catch(e => e)));\n}\n\n/**\n * Inserts gtag script tag into the page to asynchronously download gtag.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function insertScriptTag(\n dataLayerName: string,\n measurementId: string\n): void {\n const script = document.createElement('script');\n // We are not providing an analyticsId in the URL because it would trigger a `page_view`\n // without fid. We will initialize ga-id using gtag (config) command together with fid.\n script.src = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;\n script.async = true;\n document.head.appendChild(script);\n}\n\n/**\n * Get reference to, or create, global datalayer.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function getOrCreateDataLayer(dataLayerName: string): DataLayer {\n // Check for existing dataLayer and create if needed.\n let dataLayer: DataLayer = [];\n if (Array.isArray(window[dataLayerName])) {\n dataLayer = window[dataLayerName] as DataLayer;\n } else {\n window[dataLayerName] = dataLayer;\n }\n return dataLayer;\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'config' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param measurementId GA Measurement ID to set config for.\n * @param gtagParams Gtag config params to set.\n */\nasync function gtagOnConfig(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n // If config is already fetched, we know the appId and can use it to look up what FID promise we\n /// are waiting for, and wait only on that one.\n const correspondingAppId = measurementIdToAppId[measurementId as string];\n try {\n if (correspondingAppId) {\n await initializationPromisesMap[correspondingAppId];\n } else {\n // If config is not fetched yet, wait for all configs (we don't know which one we need) and\n // find the appId (if any) corresponding to this measurementId. If there is one, wait on\n // that appId's initialization promise. If there is none, promise resolves and gtag\n // call goes through.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === measurementId\n );\n if (foundConfig) {\n await initializationPromisesMap[foundConfig.appId];\n }\n }\n } catch (e) {\n logger.error(e);\n }\n gtagCore(GtagCommand.CONFIG, measurementId, gtagParams);\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'event' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementId GA Measurement ID to log event to.\n * @param gtagParams Params to log with this event.\n */\nasync function gtagOnEvent(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n try {\n let initializationPromisesToWaitFor: Array<Promise<string>> = [];\n\n // If there's a 'send_to' param, check if any ID specified matches\n // an initializeIds() promise we are waiting for.\n if (gtagParams && gtagParams['send_to']) {\n let gaSendToList: string | string[] = gtagParams['send_to'];\n // Make it an array if is isn't, so it can be dealt with the same way.\n if (!Array.isArray(gaSendToList)) {\n gaSendToList = [gaSendToList];\n }\n // Checking 'send_to' fields requires having all measurement ID results back from\n // the dynamic config fetch.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n for (const sendToId of gaSendToList) {\n // Any fetched dynamic measurement ID that matches this 'send_to' ID\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === sendToId\n );\n const initializationPromise =\n foundConfig && initializationPromisesMap[foundConfig.appId];\n if (initializationPromise) {\n initializationPromisesToWaitFor.push(initializationPromise);\n } else {\n // Found an item in 'send_to' that is not associated\n // directly with an FID, possibly a group. Empty this array,\n // exit the loop early, and let it get populated below.\n initializationPromisesToWaitFor = [];\n break;\n }\n }\n }\n\n // This will be unpopulated if there was no 'send_to' field , or\n // if not all entries in the 'send_to' field could be mapped to\n // a FID. In these cases, wait on all pending initialization promises.\n if (initializationPromisesToWaitFor.length === 0) {\n initializationPromisesToWaitFor = Object.values(\n initializationPromisesMap\n );\n }\n\n // Run core gtag function with args after all relevant initialization\n // promises have been resolved.\n await Promise.all(initializationPromisesToWaitFor);\n // Workaround for http://b/141370449 - third argument cannot be undefined.\n gtagCore(GtagCommand.EVENT, measurementId, gtagParams || {});\n } catch (e) {\n logger.error(e);\n }\n}\n\n/**\n * Wraps a standard gtag function with extra code to wait for completion of\n * relevant initialization promises before sending requests.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n */\nfunction wrapGtag(\n gtagCore: Gtag,\n /**\n * Allows wrapped gtag calls to wait on whichever intialization promises are required,\n * depending on the contents of the gtag params' `send_to` field, if any.\n */\n initializationPromisesMap: { [appId: string]: Promise<string> },\n /**\n * Wrapped gtag calls sometimes require all dynamic config fetches to have returned\n * before determining what initialization promises (which include FIDs) to wait for.\n */\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n /**\n * Wrapped gtag config calls can narrow down which initialization promise (with FID)\n * to wait for if the measurementId is already fetched, by getting the corresponding appId,\n * which is the key for the initialization promises map.\n */\n measurementIdToAppId: { [measurementId: string]: string }\n): Gtag {\n /**\n * Wrapper around gtag that ensures FID is sent with gtag calls.\n * @param command Gtag command type.\n * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.\n * @param gtagParams Params if event is EVENT/CONFIG.\n */\n async function gtagWrapper(\n command: 'config' | 'set' | 'event' | 'consent',\n idOrNameOrParams: string | ControlParams,\n gtagParams?: GtagConfigOrEventParams | ConsentSettings\n ): Promise<void> {\n try {\n // If event, check that relevant initialization promises have completed.\n if (command === GtagCommand.EVENT) {\n // If EVENT, second arg must be measurementId.\n await gtagOnEvent(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n idOrNameOrParams as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONFIG) {\n // If CONFIG, second arg must be measurementId.\n await gtagOnConfig(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n idOrNameOrParams as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONSENT) {\n // If CONFIG, second arg must be measurementId.\n gtagCore(GtagCommand.CONSENT, 'update', gtagParams as ConsentSettings);\n } else {\n // If SET, second arg must be params.\n gtagCore(GtagCommand.SET, idOrNameOrParams as CustomParams);\n }\n } catch (e) {\n logger.error(e);\n }\n }\n return gtagWrapper as Gtag;\n}\n\n/**\n * Creates global gtag function or wraps existing one if found.\n * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and\n * 'event' calls that belong to the GAID associated with this Firebase instance.\n *\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param dataLayerName Name of global GA datalayer array.\n * @param gtagFunctionName Name of global gtag function (\"gtag\" if not user-specified).\n */\nexport function wrapOrCreateGtag(\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n dataLayerName: string,\n gtagFunctionName: string\n): {\n gtagCore: Gtag;\n wrappedGtag: Gtag;\n} {\n // Create a basic core gtag function\n let gtagCore: Gtag = function (..._args: unknown[]) {\n // Must push IArguments object, not an array.\n (window[dataLayerName] as DataLayer).push(arguments);\n };\n\n // Replace it with existing one if found\n if (\n window[gtagFunctionName] &&\n typeof window[gtagFunctionName] === 'function'\n ) {\n // @ts-ignore\n gtagCore = window[gtagFunctionName];\n }\n\n window[gtagFunctionName] = wrapGtag(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId\n );\n\n return {\n gtagCore,\n wrappedGtag: window[gtagFunctionName] as Gtag\n };\n}\n\n/**\n * Returns the script tag in the DOM matching both the gtag url pattern\n * and the provided data layer name.\n */\nexport function findGtagScriptOnPage(\n dataLayerName: string\n): HTMLScriptElement | null {\n const scriptTags = window.document.getElementsByTagName('script');\n for (const tag of Object.values(scriptTags)) {\n if (\n tag.src &&\n tag.src.includes(GTAG_URL) &&\n tag.src.includes(dataLayerName)\n ) {\n return tag;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AnalyticsError {\n ALREADY_EXISTS = 'already-exists',\n ALREADY_INITIALIZED = 'already-initialized',\n ALREADY_INITIALIZED_SETTINGS = 'already-initialized-settings',\n INTEROP_COMPONENT_REG_FAILED = 'interop-component-reg-failed',\n INVALID_ANALYTICS_CONTEXT = 'invalid-analytics-context',\n INDEXEDDB_UNAVAILABLE = 'indexeddb-unavailable',\n FETCH_THROTTLE = 'fetch-throttle',\n CONFIG_FETCH_FAILED = 'config-fetch-failed',\n NO_API_KEY = 'no-api-key',\n NO_APP_ID = 'no-app-id'\n}\n\nconst ERRORS: ErrorMap<AnalyticsError> = {\n [AnalyticsError.ALREADY_EXISTS]:\n 'A Firebase Analytics instance with the appId {$id} ' +\n ' already exists. ' +\n 'Only one Firebase Analytics instance can be created for each appId.',\n [AnalyticsError.ALREADY_INITIALIZED]:\n 'initializeAnalytics() cannot be called again with different options than those ' +\n 'it was initially called with. It can be called again with the same options to ' +\n 'return the existing instance, or getAnalytics() can be used ' +\n 'to get a reference to the already-intialized instance.',\n [AnalyticsError.ALREADY_INITIALIZED_SETTINGS]:\n 'Firebase Analytics has already been initialized.' +\n 'settings() must be called before initializing any Analytics instance' +\n 'or it will have no effect.',\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]:\n 'Firebase Analytics Interop Component failed to instantiate: {$reason}',\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]:\n 'Firebase Analytics is not supported in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]:\n 'IndexedDB unavailable or restricted in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.FETCH_THROTTLE]:\n 'The config fetch request timed out while in an exponential backoff state.' +\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n [AnalyticsError.CONFIG_FETCH_FAILED]:\n 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',\n [AnalyticsError.NO_API_KEY]:\n 'The \"apiKey\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid API key.',\n [AnalyticsError.NO_APP_ID]:\n 'The \"appId\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid app ID.'\n};\n\ninterface ErrorParams {\n [AnalyticsError.ALREADY_EXISTS]: { id: string };\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]: { reason: Error };\n [AnalyticsError.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n [AnalyticsError.CONFIG_FETCH_FAILED]: {\n httpStatus: number;\n responseMessage: string;\n };\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]: { errorInfo: string };\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]: { errorInfo: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AnalyticsError, ErrorParams>(\n 'analytics',\n 'Analytics',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Most logic is copied from packages/remote-config/src/client/retrying_client.ts\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { DynamicConfig, ThrottleMetadata, MinimalDynamicConfig } from './types';\nimport { FirebaseError, calculateBackoffMillis } from '@firebase/util';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { DYNAMIC_CONFIG_URL, FETCH_TIMEOUT_MILLIS } from './constants';\nimport { logger } from './logger';\n\n// App config fields needed by analytics.\nexport interface AppFields {\n appId: string;\n apiKey: string;\n measurementId?: string;\n}\n\n/**\n * Backoff factor for 503 errors, which we want to be conservative about\n * to avoid overloading servers. Each retry interval will be\n * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one\n * will be ~30 seconds (with fuzzing).\n */\nexport const LONG_RETRY_FACTOR = 30;\n\n/**\n * Base wait interval to multiplied by backoffFactor^backoffCount.\n */\nconst BASE_INTERVAL_MILLIS = 1000;\n\n/**\n * Stubbable retry data storage class.\n */\nclass RetryData {\n constructor(\n public throttleMetadata: { [appId: string]: ThrottleMetadata } = {},\n public intervalMillis: number = BASE_INTERVAL_MILLIS\n ) {}\n\n getThrottleMetadata(appId: string): ThrottleMetadata {\n return this.throttleMetadata[appId];\n }\n\n setThrottleMetadata(appId: string, metadata: ThrottleMetadata): void {\n this.throttleMetadata[appId] = metadata;\n }\n\n deleteThrottleMetadata(appId: string): void {\n delete this.throttleMetadata[appId];\n }\n}\n\nconst defaultRetryData = new RetryData();\n\n/**\n * Set GET request headers.\n * @param apiKey App API key.\n */\nfunction getHeaders(apiKey: string): Headers {\n return new Headers({\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\n/**\n * Fetches dynamic config from backend.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfig(\n appFields: AppFields\n): Promise<DynamicConfig> {\n const { appId, apiKey } = appFields;\n const request: RequestInit = {\n method: 'GET',\n headers: getHeaders(apiKey)\n };\n const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);\n const response = await fetch(appUrl, request);\n if (response.status !== 200 && response.status !== 304) {\n let errorMessage = '';\n try {\n // Try to get any error message text from server response.\n const jsonResponse = (await response.json()) as {\n error?: { message?: string };\n };\n if (jsonResponse.error?.message) {\n errorMessage = jsonResponse.error.message;\n }\n } catch (_ignored) {}\n throw ERROR_FACTORY.create(AnalyticsError.CONFIG_FETCH_FAILED, {\n httpStatus: response.status,\n responseMessage: errorMessage\n });\n }\n return response.json();\n}\n\n/**\n * Fetches dynamic config from backend, retrying if failed.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfigWithRetry(\n app: FirebaseApp,\n // retryData and timeoutMillis are parameterized to allow passing a different value for testing.\n retryData: RetryData = defaultRetryData,\n timeoutMillis?: number\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, apiKey, measurementId } = app.options;\n\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n\n if (!apiKey) {\n if (measurementId) {\n return {\n measurementId,\n appId\n };\n }\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n\n const throttleMetadata: ThrottleMetadata = retryData.getThrottleMetadata(\n appId\n ) || {\n backoffCount: 0,\n throttleEndTimeMillis: Date.now()\n };\n\n const signal = new AnalyticsAbortSignal();\n\n setTimeout(\n async () => {\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n signal.abort();\n },\n timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS\n );\n\n return attemptFetchDynamicConfigWithRetry(\n { appId, apiKey, measurementId },\n throttleMetadata,\n signal,\n retryData\n );\n}\n\n/**\n * Runs one retry attempt.\n * @param appFields Necessary app config fields.\n * @param throttleMetadata Ongoing metadata to determine throttling times.\n * @param signal Abort signal.\n */\nasync function attemptFetchDynamicConfigWithRetry(\n appFields: AppFields,\n { throttleEndTimeMillis, backoffCount }: ThrottleMetadata,\n signal: AnalyticsAbortSignal,\n retryData: RetryData = defaultRetryData // for testing\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, measurementId } = appFields;\n // Starts with a (potentially zero) timeout to support resumption from stored state.\n // Ensures the throttle end time is honored if the last attempt timed out.\n // Note the SDK will never make a request if the fetch timeout expires at this point.\n try {\n await setAbortableTimeout(signal, throttleEndTimeMillis);\n } catch (e) {\n if (measurementId) {\n logger.warn(\n `Timed out fetching this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${\n (e as Error)?.message\n }]`\n );\n return { appId, measurementId };\n }\n throw e;\n }\n\n try {\n const response = await fetchDynamicConfig(appFields);\n\n // Note the SDK only clears throttle state if response is success or non-retriable.\n retryData.deleteThrottleMetadata(appId);\n\n return response;\n } catch (e) {\n const error = e as Error;\n if (!isRetriableError(error)) {\n retryData.deleteThrottleMetadata(appId);\n if (measurementId) {\n logger.warn(\n `Failed to fetch this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${error?.message}]`\n );\n return { appId, measurementId };\n } else {\n throw e;\n }\n }\n\n const backoffMillis =\n Number(error?.customData?.httpStatus) === 503\n ? calculateBackoffMillis(\n backoffCount,\n retryData.intervalMillis,\n LONG_RETRY_FACTOR\n )\n : calculateBackoffMillis(backoffCount, retryData.intervalMillis);\n\n // Increments backoff state.\n const throttleMetadata = {\n throttleEndTimeMillis: Date.now() + backoffMillis,\n backoffCount: backoffCount + 1\n };\n\n // Persists state.\n retryData.setThrottleMetadata(appId, throttleMetadata);\n logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);\n\n return attemptFetchDynamicConfigWithRetry(\n appFields,\n throttleMetadata,\n signal,\n retryData\n );\n }\n}\n\n/**\n * Supports waiting on a backoff by:\n *\n * <ul>\n * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>\n * <li>Listening on a signal bus for abort events, just like the Fetch API</li>\n * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled\n * request appear the same.</li>\n * </ul>\n *\n * <p>Visible for testing.\n */\nfunction setAbortableTimeout(\n signal: AnalyticsAbortSignal,\n throttleEndTimeMillis: number\n): Promise<void> {\n return new Promise((resolve, reject) => {\n // Derives backoff from given end time, normalizing negative numbers to zero.\n const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\n\n const timeout = setTimeout(resolve, backoffMillis);\n\n // Adds listener, rather than sets onabort, because signal is a shared object.\n signal.addEventListener(() => {\n clearTimeout(timeout);\n // If the request completes before this timeout, the rejection has no effect.\n reject(\n ERROR_FACTORY.create(AnalyticsError.FETCH_THROTTLE, {\n throttleEndTimeMillis\n })\n );\n });\n });\n}\n\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n if (!(e instanceof FirebaseError) || !e.customData) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e.customData['httpStatus']);\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\n/**\n * Shims a minimal AbortSignal (copied from Remote Config).\n *\n * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\n * swapped out if/when we do.\n */\nexport class AnalyticsAbortSignal {\n listeners: Array<() => void> = [];\n addEventListener(listener: () => void): void {\n this.listeners.push(listener);\n }\n abort(): void {\n this.listeners.forEach(listener => listener());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicConfig, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GA_FID_KEY, ORIGIN_KEY } from './constants';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { fetchDynamicConfigWithRetry } from './get-config';\nimport { logger } from './logger';\nimport { FirebaseApp } from '@firebase/app';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { findGtagScriptOnPage, insertScriptTag } from './helpers';\nimport { AnalyticsSettings } from './public-types';\nimport {\n defaultConsentSettingsForInit,\n _setConsentDefaultForInit,\n defaultEventParametersForInit,\n _setDefaultEventParametersForInit\n} from './functions';\n\nasync function validateIndexedDB(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: 'IndexedDB is not available in this environment.'\n }).message\n );\n return false;\n } else {\n try {\n await validateIndexedDBOpenable();\n } catch (e) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: (e as Error)?.toString()\n }).message\n );\n return false;\n }\n }\n return true;\n}\n\n/**\n * Initialize the analytics instance in gtag.js by calling config command with fid.\n *\n * NOTE: We combine analytics initialization and setting fid together because we want fid to be\n * part of the `page_view` event that's sent during the initialization\n * @param app Firebase app\n * @param gtagCore The gtag function that's not wrapped.\n * @param dynamicConfigPromisesList Array of all dynamic config promises.\n * @param measurementIdToAppId Maps measurementID to appID.\n * @param installations _FirebaseInstallationsInternal instance.\n *\n * @returns Measurement ID.\n */\nexport async function _initializeAnalytics(\n app: FirebaseApp,\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [key: string]: string },\n installations: _FirebaseInstallationsInternal,\n gtagCore: Gtag,\n dataLayerName: string,\n options?: AnalyticsSettings\n): Promise<string> {\n const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);\n // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.\n dynamicConfigPromise\n .then(config => {\n measurementIdToAppId[config.measurementId] = config.appId;\n if (\n app.options.measurementId &&\n config.measurementId !== app.options.measurementId\n ) {\n logger.warn(\n `The measurement ID in the local Firebase config (${app.options.measurementId})` +\n ` does not match the measurement ID fetched from the server (${config.measurementId}).` +\n ` To ensure analytics events are always sent to the correct Analytics property,` +\n ` update the` +\n ` measurement ID field in the local config or remove it from the local config.`\n );\n }\n })\n .catch(e => logger.error(e));\n // Add to list to track state of all dynamic config promises.\n dynamicConfigPromisesList.push(dynamicConfigPromise);\n\n const fidPromise: Promise<string | undefined> = validateIndexedDB().then(\n envIsValid => {\n if (envIsValid) {\n return installations.getId();\n } else {\n return undefined;\n }\n }\n );\n\n const [dynamicConfig, fid] = await Promise.all([\n dynamicConfigPromise,\n fidPromise\n ]);\n\n // Detect if user has already put the gtag <script> tag on this page with the passed in\n // data layer name.\n if (!findGtagScriptOnPage(dataLayerName)) {\n insertScriptTag(dataLayerName, dynamicConfig.measurementId);\n }\n\n // Detects if there are consent settings that need to be configured.\n if (defaultConsentSettingsForInit) {\n gtagCore(GtagCommand.CONSENT, 'default', defaultConsentSettingsForInit);\n _setConsentDefaultForInit(undefined);\n }\n\n // This command initializes gtag.js and only needs to be called once for the entire web app,\n // but since it is idempotent, we can call it multiple times.\n // We keep it together with other initialization logic for better code structure.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (gtagCore as any)('js', new Date());\n // User config added first. We don't want users to accidentally overwrite\n // base Firebase config properties.\n const configProperties: Record<string, unknown> = options?.config ?? {};\n\n // guard against developers accidentally setting properties with prefix `firebase_`\n configProperties[ORIGIN_KEY] = 'firebase';\n configProperties.update = true;\n\n if (fid != null) {\n configProperties[GA_FID_KEY] = fid;\n }\n\n // It should be the first config command called on this GA-ID\n // Initialize this GA-ID and set FID on it using the gtag config API.\n // Note: This will trigger a page_view event unless 'send_page_view' is set to false in\n // `configProperties`.\n gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties);\n\n // Detects if there is data that will be set on every event logged from the SDK.\n if (defaultEventParametersForInit) {\n gtagCore(GtagCommand.SET, defaultEventParametersForInit);\n _setDefaultEventParametersForInit(undefined);\n }\n\n return dynamicConfig.measurementId;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SettingsOptions, Analytics, AnalyticsSettings } from './public-types';\nimport { Gtag, DynamicConfig, MinimalDynamicConfig } from './types';\nimport { getOrCreateDataLayer, wrapOrCreateGtag } from './helpers';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { areCookiesEnabled, isBrowserExtension } from '@firebase/util';\nimport { _initializeAnalytics } from './initialize-analytics';\nimport { logger } from './logger';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\n\n/**\n * Analytics Service class.\n */\nexport class AnalyticsService implements Analytics, _FirebaseService {\n constructor(public app: FirebaseApp) {}\n _delete(): Promise<void> {\n delete initializationPromisesMap[this.app.options.appId!];\n return Promise.resolve();\n }\n}\n\n/**\n * Maps appId to full initialization promise. Wrapped gtag calls must wait on\n * all or some of these, depending on the call's `send_to` param and the status\n * of the dynamic config fetches (see below).\n */\nexport let initializationPromisesMap: {\n [appId: string]: Promise<string>; // Promise contains measurement ID string.\n} = {};\n\n/**\n * List of dynamic config fetch promises. In certain cases, wrapped gtag calls\n * wait on all these to be complete in order to determine if it can selectively\n * wait for only certain initialization (FID) promises or if it must wait for all.\n */\nlet dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n> = [];\n\n/**\n * Maps fetched measurementIds to appId. Populated when the app's dynamic config\n * fetch completes. If already populated, gtag config calls can use this to\n * selectively wait for only this app's initialization promise (FID) instead of all\n * initialization promises.\n */\nconst measurementIdToAppId: { [measurementId: string]: string } = {};\n\n/**\n * Name for window global data layer array used by GA: defaults to 'dataLayer'.\n */\nlet dataLayerName: string = 'dataLayer';\n\n/**\n * Name for window global gtag function used by GA: defaults to 'gtag'.\n */\nlet gtagName: string = 'gtag';\n\n/**\n * Reproduction of standard gtag function or reference to existing\n * gtag function on window object.\n */\nlet gtagCoreFunction: Gtag;\n\n/**\n * Wrapper around gtag function that ensures FID is sent with all\n * relevant event and config calls.\n */\nexport let wrappedGtagFunction: Gtag;\n\n/**\n * Flag to ensure page initialization steps (creation or wrapping of\n * dataLayer and gtag script) are only run once per page load.\n */\nlet globalInitDone: boolean = false;\n\n/**\n * For testing\n * @internal\n */\nexport function resetGlobalVars(\n newGlobalInitDone = false,\n newInitializationPromisesMap = {},\n newDynamicPromises = []\n): void {\n globalInitDone = newGlobalInitDone;\n initializationPromisesMap = newInitializationPromisesMap;\n dynamicConfigPromisesList = newDynamicPromises;\n dataLayerName = 'dataLayer';\n gtagName = 'gtag';\n}\n\n/**\n * For testing\n * @internal\n */\nexport function getGlobalVars(): {\n initializationPromisesMap: { [appId: string]: Promise<string> };\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >;\n} {\n return {\n initializationPromisesMap,\n dynamicConfigPromisesList\n };\n}\n\n/**\n * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.\n * Intended to be used if `gtag.js` script has been installed on\n * this page independently of Firebase Analytics, and is using non-default\n * names for either the `gtag` function or for `dataLayer`.\n * Must be called before calling `getAnalytics()` or it won't\n * have any effect.\n *\n * @public\n *\n * @param options - Custom gtag and dataLayer names.\n */\nexport function settings(options: SettingsOptions): void {\n if (globalInitDone) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n if (options.dataLayerName) {\n dataLayerName = options.dataLayerName;\n }\n if (options.gtagName) {\n gtagName = options.gtagName;\n }\n}\n\n/**\n * Returns true if no environment mismatch is found.\n * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT\n * error that also lists details for each mismatch found.\n */\nfunction warnOnBrowserContextMismatch(): void {\n const mismatchedEnvMessages = [];\n if (isBrowserExtension()) {\n mismatchedEnvMessages.push('This is a browser extension environment.');\n }\n if (!areCookiesEnabled()) {\n mismatchedEnvMessages.push('Cookies are not available.');\n }\n if (mismatchedEnvMessages.length > 0) {\n const details = mismatchedEnvMessages\n .map((message, index) => `(${index + 1}) ${message}`)\n .join(' ');\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_ANALYTICS_CONTEXT, {\n errorInfo: details\n });\n logger.warn(err.message);\n }\n}\n\n/**\n * Analytics instance factory.\n * @internal\n */\nexport function factory(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n options?: AnalyticsSettings\n): AnalyticsService {\n warnOnBrowserContextMismatch();\n const appId = app.options.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n if (!app.options.apiKey) {\n if (app.options.measurementId) {\n logger.warn(\n `The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest` +\n ` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config.`\n );\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n }\n if (initializationPromisesMap[appId] != null) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_EXISTS, {\n id: appId\n });\n }\n\n if (!globalInitDone) {\n // Steps here should only be done once per page: creation or wrapping\n // of dataLayer and global gtag function.\n\n getOrCreateDataLayer(dataLayerName);\n\n const { wrappedGtag, gtagCore } = wrapOrCreateGtag(\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n dataLayerName,\n gtagName\n );\n wrappedGtagFunction = wrappedGtag;\n gtagCoreFunction = gtagCore;\n\n globalInitDone = true;\n }\n // Async but non-blocking.\n // This map reflects the completion state of all promises for each appId.\n initializationPromisesMap[appId] = _initializeAnalytics(\n app,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n installations,\n gtagCoreFunction,\n dataLayerName,\n options\n );\n\n const analyticsInstance: AnalyticsService = new AnalyticsService(app);\n\n return analyticsInstance;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable camelcase */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport {\n Analytics,\n AnalyticsCallOptions,\n AnalyticsSettings,\n ConsentSettings,\n CustomParams,\n EventNameString,\n EventParams\n} from './public-types';\nimport { Provider } from '@firebase/component';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable,\n areCookiesEnabled,\n isBrowserExtension,\n getModularInstance,\n deepEqual\n} from '@firebase/util';\nimport { ANALYTICS_TYPE, GtagCommand } from './constants';\nimport {\n AnalyticsService,\n initializationPromisesMap,\n wrappedGtagFunction\n} from './factory';\nimport { logger } from './logger';\nimport {\n logEvent as internalLogEvent,\n setCurrentScreen as internalSetCurrentScreen,\n setUserId as internalSetUserId,\n setUserProperties as internalSetUserProperties,\n setAnalyticsCollectionEnabled as internalSetAnalyticsCollectionEnabled,\n _setConsentDefaultForInit,\n _setDefaultEventParametersForInit\n} from './functions';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\n\nexport { settings } from './factory';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [ANALYTICS_TYPE]: AnalyticsService;\n }\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function getAnalytics(app: FirebaseApp = getApp()): Analytics {\n app = getModularInstance(app);\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n\n if (analyticsProvider.isInitialized()) {\n return analyticsProvider.getImmediate();\n }\n\n return initializeAnalytics(app);\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function initializeAnalytics(\n app: FirebaseApp,\n options: AnalyticsSettings = {}\n): Analytics {\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n if (analyticsProvider.isInitialized()) {\n const existingInstance = analyticsProvider.getImmediate();\n if (deepEqual(options, analyticsProvider.getOptions())) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n }\n const analyticsInstance = analyticsProvider.initialize({ options });\n return analyticsInstance;\n}\n\n/**\n * This is a public static method provided to users that wraps four different checks:\n *\n * 1. Check if it's not a browser extension environment.\n * 2. Check if cookies are enabled in current browser.\n * 3. Check if IndexedDB is supported by the browser environment.\n * 4. Check if the current browser context is valid for using `IndexedDB.open()`.\n *\n * @public\n *\n */\nexport async function isSupported(): Promise<boolean> {\n if (isBrowserExtension()) {\n return false;\n }\n if (!areCookiesEnabled()) {\n return false;\n }\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n try {\n const isDBOpenable: boolean = await validateIndexedDBOpenable();\n return isDBOpenable;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Use gtag `config` command to set `screen_name`.\n *\n * @public\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param screenName - Screen name to set.\n */\nexport function setCurrentScreen(\n analyticsInstance: Analytics,\n screenName: string,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetCurrentScreen(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n screenName,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Use gtag `config` command to set `user_id`.\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param id - User ID to set.\n */\nexport function setUserId(\n analyticsInstance: Analytics,\n id: string | null,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n id,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Use gtag `config` command to set all params specified.\n *\n * @public\n */\nexport function setUserProperties(\n analyticsInstance: Analytics,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserProperties(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n properties,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Sets whether Google Analytics collection is enabled for this app on this device.\n * Sets global `window['ga-disable-analyticsId'] = true;`\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param enabled - If true, enables collection, if false, disables it.\n */\nexport function setAnalyticsCollectionEnabled(\n analyticsInstance: Analytics,\n enabled: boolean\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetAnalyticsCollectionEnabled(\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n enabled\n ).catch(e => logger.error(e));\n}\n\n/**\n * Adds data that will be set on every event logged from the SDK, including automatic ones.\n * With gtag's \"set\" command, the values passed persist on the current page and are passed with\n * all subsequent events.\n * @public\n * @param customParams - Any custom params the user may pass to gtag.js.\n */\nexport function setDefaultEventParameters(customParams: CustomParams): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.SET, customParams);\n } else {\n _setDefaultEventParametersForInit(customParams);\n }\n}\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_payment_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n payment_type?: EventParams['payment_type'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_shipping_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n shipping_tier?: EventParams['shipping_tier'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart',\n eventParams?: {\n currency?: EventParams['currency'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'begin_checkout',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'checkout_progress',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/exceptions\n * | Measure exceptions}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'exception',\n eventParams?: {\n description?: EventParams['description'];\n fatal?: EventParams['fatal'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'generate_lead',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'login',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view\n * | Page views}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'page_view',\n eventParams?: {\n page_title?: string;\n page_location?: string;\n page_path?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'purchase' | 'refund',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n transaction_id: EventParams['transaction_id'];\n tax?: EventParams['tax'];\n shipping?: EventParams['shipping'];\n items?: EventParams['items'];\n coupon?: EventParams['coupon'];\n affiliation?: EventParams['affiliation'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See {@link https://firebase.google.com/docs/analytics/screenviews\n * | Track Screenviews}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'screen_view',\n eventParams?: {\n firebase_screen: EventParams['firebase_screen'];\n firebase_screen_class: EventParams['firebase_screen_class'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'search' | 'view_search_results',\n eventParams?: {\n search_term?: EventParams['search_term'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_content',\n eventParams?: {\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_item',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_promotion' | 'view_promotion',\n eventParams?: {\n items?: EventParams['items'];\n promotion_id?: EventParams['promotion_id'];\n promotion_name?: EventParams['promotion_name'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'set_checkout_option',\n eventParams?: {\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'share',\n eventParams?: {\n method?: EventParams['method'];\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'sign_up',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'timing_complete',\n eventParams?: {\n name: string;\n value: number;\n event_category?: string;\n event_label?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_cart' | 'view_item',\n eventParams?: {\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_item_list',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent<T extends string>(\n analyticsInstance: Analytics,\n eventName: CustomEventName<T>,\n eventParams?: { [key: string]: any },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * List of official event parameters can be found in the gtag.js\n * reference documentation:\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n *\n * @public\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalLogEvent(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n eventName,\n eventParams,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Any custom event name string not in the standard list of recommended\n * event names.\n * @public\n */\nexport type CustomEventName<T> = T extends EventNameString ? never : T;\n\n/**\n * Sets the applicable end user consent state for this web app across all gtag references once\n * Firebase Analytics is initialized.\n *\n * Use the {@link ConsentSettings} to specify individual consent type values. By default consent\n * types are set to \"granted\".\n * @public\n * @param consentSettings - Maps the applicable end user consent state for gtag.js.\n */\nexport function setConsent(consentSettings: ConsentSettings): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.CONSENT, 'update', consentSettings);\n } else {\n _setConsentDefaultForInit(consentSettings);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AnalyticsCallOptions,\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { Gtag } from './types';\nimport { GtagCommand } from './constants';\n\n/**\n * Event parameters to set on 'gtag' during initialization.\n */\nexport let defaultEventParametersForInit: CustomParams | undefined;\n\n/**\n * Logs an analytics event through the Firebase SDK.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param eventName Google Analytics event name, choose from standard list or use a custom string.\n * @param eventParams Analytics event parameters.\n */\nexport async function logEvent(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.EVENT, eventName, eventParams);\n return;\n } else {\n const measurementId = await initializationPromise;\n const params: EventParams | ControlParams = {\n ...eventParams,\n 'send_to': measurementId\n };\n gtagFunction(GtagCommand.EVENT, eventName, params);\n }\n}\n\n/**\n * Set screen_name parameter for this Google Analytics ID.\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param screenName Screen name string to set.\n */\nexport async function setCurrentScreen(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n screenName: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'screen_name': screenName });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'screen_name': screenName\n });\n }\n}\n\n/**\n * Set user_id parameter for this Google Analytics ID.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param id User ID string to set\n */\nexport async function setUserId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n id: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'user_id': id });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_id': id\n });\n }\n}\n\n/**\n * Set all other user properties other than user_id and screen_name.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param properties Map of user properties to set\n */\nexport async function setUserProperties(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n const flatProperties: { [key: string]: unknown } = {};\n for (const key of Object.keys(properties)) {\n // use dot notation for merge behavior in gtag.js\n flatProperties[`user_properties.${key}`] = properties[key];\n }\n gtagFunction(GtagCommand.SET, flatProperties);\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_properties': properties\n });\n }\n}\n\n/**\n * Set whether collection is enabled for this ID.\n *\n * @param enabled If true, collection is enabled for this ID.\n */\nexport async function setAnalyticsCollectionEnabled(\n initializationPromise: Promise<string>,\n enabled: boolean\n): Promise<void> {\n const measurementId = await initializationPromise;\n window[`ga-disable-${measurementId}`] = !enabled;\n}\n\n/**\n * Consent parameters to default to during 'gtag' initialization.\n */\nexport let defaultConsentSettingsForInit: ConsentSettings | undefined;\n\n/**\n * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of\n * analytics.\n *\n * @param consentSettings Maps the applicable end user consent state for gtag.js.\n */\nexport function _setConsentDefaultForInit(\n consentSettings?: ConsentSettings\n): void {\n defaultConsentSettingsForInit = consentSettings;\n}\n\n/**\n * Sets the variable `defaultEventParametersForInit` for use in the initialization of\n * analytics.\n *\n * @param customParams Any custom params the user may pass to gtag.js.\n */\nexport function _setDefaultEventParametersForInit(\n customParams?: CustomParams\n): void {\n defaultEventParametersForInit = customParams;\n}\n","/**\n * Firebase Analytics\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types';\nimport { factory } from './factory';\nimport { ANALYTICS_TYPE } from './constants';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { logEvent } from './api';\nimport { name, version } from '../package.json';\nimport { AnalyticsCallOptions } from './public-types';\nimport '@firebase/installations';\n\ndeclare global {\n interface Window {\n [key: string]: unknown;\n }\n}\n\nfunction registerAnalytics(): void {\n _registerComponent(\n new Component(\n ANALYTICS_TYPE,\n (container, { options: analyticsOptions }: InstanceFactoryOptions) => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\n return factory(app, installations, analyticsOptions);\n },\n ComponentType.PUBLIC\n )\n );\n\n _registerComponent(\n new Component('analytics-internal', internalFactory, ComponentType.PRIVATE)\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n\n function internalFactory(\n container: ComponentContainer\n ): FirebaseAnalyticsInternal {\n try {\n const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();\n return {\n logEvent: (\n eventName: string,\n eventParams?: { [key: string]: unknown },\n options?: AnalyticsCallOptions\n ) => logEvent(analytics, eventName, eventParams, options)\n };\n } catch (e) {\n throw ERROR_FACTORY.create(AnalyticsError.INTEROP_COMPONENT_REG_FAILED, {\n reason: e as Error\n });\n }\n }\n}\n\nregisterAnalytics();\n\nexport * from './api';\nexport * from './public-types';\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Officially recommended event names for gtag.js\n * Any other string is also allowed.\n */\nexport enum EventName {\n ADD_SHIPPING_INFO = 'add_shipping_info',\n ADD_PAYMENT_INFO = 'add_payment_info',\n ADD_TO_CART = 'add_to_cart',\n ADD_TO_WISHLIST = 'add_to_wishlist',\n BEGIN_CHECKOUT = 'begin_checkout',\n /**\n * @deprecated\n * This event name is deprecated and is unsupported in updated\n * Enhanced Ecommerce reports.\n */\n CHECKOUT_PROGRESS = 'checkout_progress',\n EXCEPTION = 'exception',\n GENERATE_LEAD = 'generate_lead',\n LOGIN = 'login',\n PAGE_VIEW = 'page_view',\n PURCHASE = 'purchase',\n REFUND = 'refund',\n REMOVE_FROM_CART = 'remove_from_cart',\n SCREEN_VIEW = 'screen_view',\n SEARCH = 'search',\n SELECT_CONTENT = 'select_content',\n SELECT_ITEM = 'select_item',\n SELECT_PROMOTION = 'select_promotion',\n /** @deprecated */\n SET_CHECKOUT_OPTION = 'set_checkout_option',\n SHARE = 'share',\n SIGN_UP = 'sign_up',\n TIMING_COMPLETE = 'timing_complete',\n VIEW_CART = 'view_cart',\n VIEW_ITEM = 'view_item',\n VIEW_ITEM_LIST = 'view_item_list',\n VIEW_PROMOTION = 'view_promotion',\n VIEW_SEARCH_RESULTS = 'view_search_results'\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, {\n _FirebaseNamespace,\n FirebaseApp\n} from '@firebase/app-compat';\nimport { FirebaseAnalytics } from '@firebase/analytics-types';\nimport { name, version } from '../package.json';\nimport { AnalyticsService } from './service';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport {\n settings as settingsExp,\n isSupported as isSupportedExp\n} from '@firebase/analytics';\nimport { EventName } from './constants';\n\nconst factory: InstanceFactory<'analytics-compat'> = (\n container: ComponentContainer\n) => {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const analyticsServiceExp = container.getProvider('analytics').getImmediate();\n\n return new AnalyticsService(app as FirebaseApp, analyticsServiceExp);\n};\n\nexport function registerAnalytics(): void {\n const namespaceExports = {\n Analytics: AnalyticsService,\n settings: settingsExp,\n isSupported: isSupportedExp,\n // We removed this enum in exp so need to re-create it here for compat.\n EventName\n };\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component('analytics-compat', factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n}\n\nregisterAnalytics();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerAnalytics`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n analytics(app?: FirebaseApp): FirebaseAnalytics;\n }\n interface FirebaseApp {\n analytics(): FirebaseAnalytics;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AnalyticsCallOptions,\n CustomParams,\n EventParams,\n FirebaseAnalytics\n} from '@firebase/analytics-types';\nimport {\n Analytics as AnalyticsServiceExp,\n logEvent as logEventExp,\n setAnalyticsCollectionEnabled as setAnalyticsCollectionEnabledExp,\n setCurrentScreen as setCurrentScreenExp,\n setUserId as setUserIdExp,\n setUserProperties as setUserPropertiesExp\n} from '@firebase/analytics';\nimport { _FirebaseService, FirebaseApp } from '@firebase/app-compat';\n\nexport class AnalyticsService implements FirebaseAnalytics, _FirebaseService {\n constructor(\n public app: FirebaseApp,\n readonly _delegate: AnalyticsServiceExp\n ) {}\n\n logEvent(\n eventName: string,\n eventParams?: EventParams | CustomParams,\n options?: AnalyticsCallOptions\n ): void {\n logEventExp(this._delegate, eventName as '', eventParams, options);\n }\n\n /**\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n */\n setCurrentScreen(screenName: string, options?: AnalyticsCallOptions): void {\n setCurrentScreenExp(this._delegate, screenName, options);\n }\n\n setUserId(id: string, options?: AnalyticsCallOptions): void {\n setUserIdExp(this._delegate, id, options);\n }\n\n setUserProperties(\n properties: CustomParams,\n options?: AnalyticsCallOptions\n ): void {\n setUserPropertiesExp(this._delegate, properties, options);\n }\n\n setAnalyticsCollectionEnabled(enabled: boolean): void {\n setAnalyticsCollectionEnabledExp(this._delegate, enabled);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n AppCheckProvider,\n AppCheckTokenInternal,\n AppCheckTokenObserver\n} from './types';\nimport { Refresher } from './proactive-refresh';\nimport { Deferred } from '@firebase/util';\nimport { GreCAPTCHA } from './recaptcha';\nexport interface AppCheckState {\n activated: boolean;\n tokenObservers: AppCheckTokenObserver[];\n provider?: AppCheckProvider;\n token?: AppCheckTokenInternal;\n cachedTokenPromise?: Promise<AppCheckTokenInternal | undefined>;\n exchangeTokenPromise?: Promise<AppCheckTokenInternal>;\n tokenRefresher?: Refresher;\n reCAPTCHAState?: ReCAPTCHAState;\n isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n initialized: Deferred<GreCAPTCHA>;\n widgetId?: string;\n}\n\nexport interface DebugState {\n initialized: boolean;\n enabled: boolean;\n token?: Deferred<string>;\n}\n\nconst APP_CHECK_STATES = new Map<FirebaseApp, AppCheckState>();\nexport const DEFAULT_STATE: AppCheckState = {\n activated: false,\n tokenObservers: []\n};\n\nconst DEBUG_STATE: DebugState = {\n initialized: false,\n enabled: false\n};\n\n/**\n * Gets a reference to the state object.\n */\nexport function getStateReference(app: FirebaseApp): AppCheckState {\n return APP_CHECK_STATES.get(app) || { ...DEFAULT_STATE };\n}\n\n/**\n * Set once on initialization. The map should hold the same reference to the\n * same object until this entry is deleted.\n */\nexport function setInitialState(\n app: FirebaseApp,\n state: AppCheckState\n): AppCheckState {\n APP_CHECK_STATES.set(app, state);\n return APP_CHECK_STATES.get(app) as AppCheckState;\n}\n\n// for testing only\nexport function clearState(): void {\n APP_CHECK_STATES.clear();\n DEBUG_STATE.enabled = false;\n DEBUG_STATE.token = undefined;\n DEBUG_STATE.initialized = false;\n}\n\nexport function getDebugState(): DebugState {\n return DEBUG_STATE;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const BASE_ENDPOINT =\n 'https://content-firebaseappcheck.googleapis.com/v1';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaV3Token';\nexport const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD =\n 'exchangeRecaptchaEnterpriseToken';\nexport const EXCHANGE_DEBUG_TOKEN_METHOD = 'exchangeDebugToken';\n\nexport const TOKEN_REFRESH_TIME = {\n /**\n * The offset time before token natural expiration to run the refresh.\n * This is currently 5 minutes.\n */\n OFFSET_DURATION: 5 * 60 * 1000,\n /**\n * This is the first retrial wait after an error. This is currently\n * 30 seconds.\n */\n RETRIAL_MIN_WAIT: 30 * 1000,\n /**\n * This is the maximum retrial wait, currently 16 minutes.\n */\n RETRIAL_MAX_WAIT: 16 * 60 * 1000\n};\n\n/**\n * One day in millis, for certain error code backoffs.\n */\nexport const ONE_DAY = 24 * 60 * 60 * 1000;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\n/**\n * Port from auth proactiverefresh.js\n *\n */\n// TODO: move it to @firebase/util?\n// TODO: allow to config whether refresh should happen in the background\nexport class Refresher {\n private pending: Deferred<unknown> | null = null;\n private nextErrorWaitInterval: number;\n constructor(\n private readonly operation: () => Promise<unknown>,\n private readonly retryPolicy: (error: unknown) => boolean,\n private readonly getWaitDuration: () => number,\n private readonly lowerBound: number,\n private readonly upperBound: number\n ) {\n this.nextErrorWaitInterval = lowerBound;\n\n if (lowerBound > upperBound) {\n throw new Error(\n 'Proactive refresh lower bound greater than upper bound!'\n );\n }\n }\n\n start(): void {\n this.nextErrorWaitInterval = this.lowerBound;\n this.process(true).catch(() => {\n /* we don't care about the result */\n });\n }\n\n stop(): void {\n if (this.pending) {\n this.pending.reject('cancelled');\n this.pending = null;\n }\n }\n\n isRunning(): boolean {\n return !!this.pending;\n }\n\n private async process(hasSucceeded: boolean): Promise<void> {\n this.stop();\n try {\n this.pending = new Deferred();\n await sleep(this.getNextRun(hasSucceeded));\n\n // Why do we resolve a promise, then immediate wait for it?\n // We do it to make the promise chain cancellable.\n // We can call stop() which rejects the promise before the following line execute, which makes\n // the code jump to the catch block.\n // TODO: unit test this\n this.pending.resolve();\n await this.pending.promise;\n this.pending = new Deferred();\n await this.operation();\n\n this.pending.resolve();\n await this.pending.promise;\n\n this.process(true).catch(() => {\n /* we don't care about the result */\n });\n } catch (error) {\n if (this.retryPolicy(error)) {\n this.process(false).catch(() => {\n /* we don't care about the result */\n });\n } else {\n this.stop();\n }\n }\n }\n\n private getNextRun(hasSucceeded: boolean): number {\n if (hasSucceeded) {\n // If last operation succeeded, reset next error wait interval and return\n // the default wait duration.\n this.nextErrorWaitInterval = this.lowerBound;\n // Return typical wait duration interval after a successful operation.\n return this.getWaitDuration();\n } else {\n // Get next error wait interval.\n const currentErrorWaitInterval = this.nextErrorWaitInterval;\n // Double interval for next consecutive error.\n this.nextErrorWaitInterval *= 2;\n // Make sure next wait interval does not exceed the maximum upper bound.\n if (this.nextErrorWaitInterval > this.upperBound) {\n this.nextErrorWaitInterval = this.upperBound;\n }\n return currentErrorWaitInterval;\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n ALREADY_INITIALIZED = 'already-initialized',\n USE_BEFORE_ACTIVATION = 'use-before-activation',\n FETCH_NETWORK_ERROR = 'fetch-network-error',\n FETCH_PARSE_ERROR = 'fetch-parse-error',\n FETCH_STATUS_ERROR = 'fetch-status-error',\n STORAGE_OPEN = 'storage-open',\n STORAGE_GET = 'storage-get',\n STORAGE_WRITE = 'storage-set',\n RECAPTCHA_ERROR = 'recaptcha-error',\n THROTTLED = 'throttled'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n [AppCheckError.ALREADY_INITIALIZED]:\n 'You have already called initializeAppCheck() for FirebaseApp {$appName} with ' +\n 'different options. To avoid this error, call initializeAppCheck() with the ' +\n 'same options as when it was originally called. This will return the ' +\n 'already initialized instance.',\n [AppCheckError.USE_BEFORE_ACTIVATION]:\n 'App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. ' +\n 'Call initializeAppCheck() before instantiating other Firebase services.',\n [AppCheckError.FETCH_NETWORK_ERROR]:\n 'Fetch failed to connect to a network. Check Internet connection. ' +\n 'Original error: {$originalErrorMessage}.',\n [AppCheckError.FETCH_PARSE_ERROR]:\n 'Fetch client could not parse response.' +\n ' Original error: {$originalErrorMessage}.',\n [AppCheckError.FETCH_STATUS_ERROR]:\n 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n [AppCheckError.STORAGE_OPEN]:\n 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.STORAGE_GET]:\n 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.STORAGE_WRITE]:\n 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.RECAPTCHA_ERROR]: 'ReCAPTCHA error.',\n [AppCheckError.THROTTLED]: `Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}`\n};\n\ninterface ErrorParams {\n [AppCheckError.ALREADY_INITIALIZED]: { appName: string };\n [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n [AppCheckError.FETCH_NETWORK_ERROR]: { originalErrorMessage: string };\n [AppCheckError.FETCH_PARSE_ERROR]: { originalErrorMessage: string };\n [AppCheckError.FETCH_STATUS_ERROR]: { httpStatus: number };\n [AppCheckError.STORAGE_OPEN]: { originalErrorMessage?: string };\n [AppCheckError.STORAGE_GET]: { originalErrorMessage?: string };\n [AppCheckError.STORAGE_WRITE]: { originalErrorMessage?: string };\n [AppCheckError.THROTTLED]: { time: string; httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n 'appCheck',\n 'AppCheck',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GreCAPTCHA } from './recaptcha';\nimport { getStateReference } from './state';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getRecaptcha(\n isEnterprise: boolean = false\n): GreCAPTCHA | undefined {\n if (isEnterprise) {\n return self.grecaptcha?.enterprise;\n }\n return self.grecaptcha;\n}\n\nexport function ensureActivated(app: FirebaseApp): void {\n if (!getStateReference(app).activated) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: app.name\n });\n }\n}\n\nexport function getDurationString(durationInMillis: number): string {\n const totalSeconds = Math.round(durationInMillis / 1000);\n const days = Math.floor(totalSeconds / (3600 * 24));\n const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);\n const minutes = Math.floor(\n (totalSeconds - days * 3600 * 24 - hours * 3600) / 60\n );\n const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;\n\n let result = '';\n if (days) {\n result += pad(days) + 'd:';\n }\n if (hours) {\n result += pad(hours) + 'h:';\n }\n result += pad(minutes) + 'm:' + pad(seconds) + 's';\n return result;\n}\n\nfunction pad(value: number): string {\n if (value === 0) {\n return '00';\n }\n return value >= 10 ? value.toString() : '0' + value;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BASE_ENDPOINT,\n EXCHANGE_DEBUG_TOKEN_METHOD,\n EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD,\n EXCHANGE_RECAPTCHA_TOKEN_METHOD\n} from './constants';\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { Provider } from '@firebase/component';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Response JSON returned from AppCheck server endpoint.\n */\ninterface AppCheckResponse {\n token: string;\n // timeToLive\n ttl: string;\n}\n\ninterface AppCheckRequest {\n url: string;\n body: { [key: string]: string };\n}\n\nexport async function exchangeToken(\n { url, body }: AppCheckRequest,\n heartbeatServiceProvider: Provider<'heartbeat'>\n): Promise<AppCheckTokenInternal> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json'\n };\n // If heartbeat service exists, add heartbeat header string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers['X-Firebase-Client'] = heartbeatsHeader;\n }\n }\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify(body),\n headers\n };\n let response;\n try {\n response = await fetch(url, options);\n } catch (originalError) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_NETWORK_ERROR, {\n originalErrorMessage: (originalError as Error)?.message\n });\n }\n\n if (response.status !== 200) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_STATUS_ERROR, {\n httpStatus: response.status\n });\n }\n\n let responseBody: AppCheckResponse;\n try {\n // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n responseBody = await response.json();\n } catch (originalError) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n originalErrorMessage: (originalError as Error)?.message\n });\n }\n\n // Protobuf duration format.\n // https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Duration\n const match = responseBody.ttl.match(/^([\\d.]+)(s)$/);\n if (!match || !match[2] || isNaN(Number(match[1]))) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n originalErrorMessage:\n `ttl field (timeToLive) is not in standard Protobuf Duration ` +\n `format: ${responseBody.ttl}`\n });\n }\n const timeToLiveAsNumber = Number(match[1]) * 1000;\n\n const now = Date.now();\n return {\n token: responseBody.token,\n expireTimeMillis: now + timeToLiveAsNumber,\n issuedAtTimeMillis: now\n };\n}\n\nexport function getExchangeRecaptchaV3TokenRequest(\n app: FirebaseApp,\n reCAPTCHAToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n 'recaptcha_v3_token': reCAPTCHAToken\n }\n };\n}\n\nexport function getExchangeRecaptchaEnterpriseTokenRequest(\n app: FirebaseApp,\n reCAPTCHAToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n 'recaptcha_enterprise_token': reCAPTCHAToken\n }\n };\n}\n\nexport function getExchangeDebugTokenRequest(\n app: FirebaseApp,\n debugToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n // eslint-disable-next-line\n debug_token: debugToken\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { AppCheckTokenInternal } from './types';\nconst DB_NAME = 'firebase-app-check-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-app-check-store';\nconst DEBUG_TOKEN_KEY = 'debug-token';\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\nfunction getDBPromise(): Promise<IDBDatabase> {\n if (dbPromise) {\n return dbPromise;\n }\n\n dbPromise = new Promise((resolve, reject) => {\n try {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n request.onsuccess = event => {\n resolve((event.target as IDBOpenDBRequest).result);\n };\n\n request.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n\n request.onupgradeneeded = event => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (event.oldVersion) {\n case 0:\n db.createObjectStore(STORE_NAME, {\n keyPath: 'compositeKey'\n });\n }\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n originalErrorMessage: (e as Error)?.message\n })\n );\n }\n });\n\n return dbPromise;\n}\n\nexport function readTokenFromIndexedDB(\n app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n return read(computeKey(app)) as Promise<AppCheckTokenInternal | undefined>;\n}\n\nexport function writeTokenToIndexedDB(\n app: FirebaseApp,\n token?: AppCheckTokenInternal\n): Promise<void> {\n return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise<void> {\n return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise<string | undefined> {\n return read(DEBUG_TOKEN_KEY) as Promise<string | undefined>;\n}\n\nasync function write(key: string, value: unknown): Promise<void> {\n const db = await getDBPromise();\n\n const transaction = db.transaction(STORE_NAME, 'readwrite');\n const store = transaction.objectStore(STORE_NAME);\n const request = store.put({\n compositeKey: key,\n value\n });\n\n return new Promise((resolve, reject) => {\n request.onsuccess = _event => {\n resolve();\n };\n\n transaction.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_WRITE, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n });\n}\n\nasync function read(key: string): Promise<unknown> {\n const db = await getDBPromise();\n\n const transaction = db.transaction(STORE_NAME, 'readonly');\n const store = transaction.objectStore(STORE_NAME);\n const request = store.get(key);\n\n return new Promise((resolve, reject) => {\n request.onsuccess = event => {\n const result = (event.target as IDBRequest).result;\n\n if (result) {\n resolve(result.value);\n } else {\n resolve(undefined);\n }\n };\n\n transaction.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_GET, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n });\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.options.appId}-${app.name}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-check');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { isIndexedDBAvailable, uuidv4 } from '@firebase/util';\nimport {\n readDebugTokenFromIndexedDB,\n readTokenFromIndexedDB,\n writeDebugTokenToIndexedDB,\n writeTokenToIndexedDB\n} from './indexeddb';\nimport { logger } from './logger';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Always resolves. In case of an error reading from indexeddb, resolve with undefined\n */\nexport async function readTokenFromStorage(\n app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n if (isIndexedDBAvailable()) {\n let token = undefined;\n try {\n token = await readTokenFromIndexedDB(app);\n } catch (e) {\n // swallow the error and return undefined\n logger.warn(`Failed to read token from IndexedDB. Error: ${e}`);\n }\n return token;\n }\n\n return undefined;\n}\n\n/**\n * Always resolves. In case of an error writing to indexeddb, print a warning and resolve the promise\n */\nexport function writeTokenToStorage(\n app: FirebaseApp,\n token?: AppCheckTokenInternal\n): Promise<void> {\n if (isIndexedDBAvailable()) {\n return writeTokenToIndexedDB(app, token).catch(e => {\n // swallow the error and resolve the promise\n logger.warn(`Failed to write token to IndexedDB. Error: ${e}`);\n });\n }\n\n return Promise.resolve();\n}\n\nexport async function readOrCreateDebugTokenFromStorage(): Promise<string> {\n /**\n * Theoretically race condition can happen if we read, then write in 2 separate transactions.\n * But it won't happen here, because this function will be called exactly once.\n */\n let existingDebugToken: string | undefined = undefined;\n try {\n existingDebugToken = await readDebugTokenFromIndexedDB();\n } catch (_e) {\n // failed to read from indexeddb. We assume there is no existing debug token, and generate a new one.\n }\n\n if (!existingDebugToken) {\n // create a new debug token\n const newToken = uuidv4();\n // We don't need to block on writing to indexeddb\n // In case persistence failed, a new debug token will be generated everytime the page is refreshed.\n // It renders the debug token useless because you have to manually register(whitelist) the new token in the firebase console again and again.\n // If you see this error trying to use debug token, it probably means you are using a browser that doesn't support indexeddb.\n // You should switch to a different browser that supports indexeddb\n writeDebugTokenToIndexedDB(newToken).catch(e =>\n logger.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)\n );\n return newToken;\n } else {\n return existingDebugToken;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getDebugState } from './state';\nimport { readOrCreateDebugTokenFromStorage } from './storage';\nimport { Deferred, getGlobal } from '@firebase/util';\n\ndeclare global {\n // var must be used for global scopes\n // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis\n // eslint-disable-next-line no-var\n var FIREBASE_APPCHECK_DEBUG_TOKEN: boolean | string | undefined;\n}\n\nexport function isDebugMode(): boolean {\n const debugState = getDebugState();\n return debugState.enabled;\n}\n\nexport async function getDebugToken(): Promise<string> {\n const state = getDebugState();\n\n if (state.enabled && state.token) {\n return state.token.promise;\n } else {\n // should not happen!\n throw Error(`\n Can't get debug token in production mode.\n `);\n }\n}\n\nexport function initializeDebugMode(): void {\n const globals = getGlobal();\n const debugState = getDebugState();\n // Set to true if this function has been called, whether or not\n // it enabled debug mode.\n debugState.initialized = true;\n\n if (\n typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&\n globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true\n ) {\n return;\n }\n\n debugState.enabled = true;\n const deferredToken = new Deferred<string>();\n debugState.token = deferredToken;\n\n if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === 'string') {\n deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);\n } else {\n deferredToken.resolve(readOrCreateDebugTokenFromStorage());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n AppCheckTokenResult,\n AppCheckTokenInternal,\n AppCheckTokenObserver,\n ListenerType\n} from './types';\nimport { AppCheckTokenListener } from './public-types';\nimport { getStateReference } from './state';\nimport { TOKEN_REFRESH_TIME } from './constants';\nimport { Refresher } from './proactive-refresh';\nimport { ensureActivated } from './util';\nimport { exchangeToken, getExchangeDebugTokenRequest } from './client';\nimport { writeTokenToStorage } from './storage';\nimport { getDebugToken, isDebugMode } from './debug';\nimport { base64, FirebaseError } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\nimport { AppCheckError } from './errors';\n\n// Initial hardcoded value agreed upon across platforms for initial launch.\n// Format left open for possible dynamic error values and other fields in the future.\nexport const defaultTokenErrorData = { error: 'UNKNOWN_ERROR' };\n\n/**\n * Stringify and base64 encode token error data.\n *\n * @param tokenError Error data, currently hardcoded.\n */\nexport function formatDummyToken(\n tokenErrorData: Record<string, string>\n): string {\n return base64.encodeString(\n JSON.stringify(tokenErrorData),\n /* webSafe= */ false\n );\n}\n\n/**\n * This function always resolves.\n * The result will contain an error field if there is any error.\n * In case there is an error, the token field in the result will be populated with a dummy value\n */\nexport async function getToken(\n appCheck: AppCheckService,\n forceRefresh = false\n): Promise<AppCheckTokenResult> {\n const app = appCheck.app;\n ensureActivated(app);\n\n const state = getStateReference(app);\n\n /**\n * First check if there is a token in memory from a previous `getToken()` call.\n */\n let token: AppCheckTokenInternal | undefined = state.token;\n let error: Error | undefined = undefined;\n\n /**\n * If an invalid token was found in memory, clear token from\n * memory and unset the local variable `token`.\n */\n if (token && !isValid(token)) {\n state.token = undefined;\n token = undefined;\n }\n\n /**\n * If there is no valid token in memory, try to load token from indexedDB.\n */\n if (!token) {\n // cachedTokenPromise contains the token found in IndexedDB or undefined if not found.\n const cachedToken = await state.cachedTokenPromise;\n if (cachedToken) {\n if (isValid(cachedToken)) {\n token = cachedToken;\n } else {\n // If there was an invalid token in the indexedDB cache, clear it.\n await writeTokenToStorage(app, undefined);\n }\n }\n }\n\n // Return the cached token (from either memory or indexedDB) if it's valid\n if (!forceRefresh && token && isValid(token)) {\n return {\n token: token.token\n };\n }\n\n // Only set to true if this `getToken()` call is making the actual\n // REST call to the exchange endpoint, versus waiting for an already\n // in-flight call (see debug and regular exchange endpoint paths below)\n let shouldCallListeners = false;\n\n /**\n * DEBUG MODE\n * If debug mode is set, and there is no cached token, fetch a new App\n * Check token using the debug token, and return it directly.\n */\n if (isDebugMode()) {\n // Avoid making another call to the exchange endpoint if one is in flight.\n if (!state.exchangeTokenPromise) {\n state.exchangeTokenPromise = exchangeToken(\n getExchangeDebugTokenRequest(app, await getDebugToken()),\n appCheck.heartbeatServiceProvider\n ).finally(() => {\n // Clear promise when settled - either resolved or rejected.\n state.exchangeTokenPromise = undefined;\n });\n shouldCallListeners = true;\n }\n const tokenFromDebugExchange: AppCheckTokenInternal =\n await state.exchangeTokenPromise;\n // Write debug token to indexedDB.\n await writeTokenToStorage(app, tokenFromDebugExchange);\n // Write debug token to state.\n state.token = tokenFromDebugExchange;\n return { token: tokenFromDebugExchange.token };\n }\n\n /**\n * There are no valid tokens in memory or indexedDB and we are not in\n * debug mode.\n * Request a new token from the exchange endpoint.\n */\n try {\n // Avoid making another call to the exchange endpoint if one is in flight.\n if (!state.exchangeTokenPromise) {\n // state.provider is populated in initializeAppCheck()\n // ensureActivated() at the top of this function checks that\n // initializeAppCheck() has been called.\n state.exchangeTokenPromise = state.provider!.getToken().finally(() => {\n // Clear promise when settled - either resolved or rejected.\n state.exchangeTokenPromise = undefined;\n });\n shouldCallListeners = true;\n }\n token = await getStateReference(app).exchangeTokenPromise;\n } catch (e) {\n if ((e as FirebaseError).code === `appCheck/${AppCheckError.THROTTLED}`) {\n // Warn if throttled, but do not treat it as an error.\n logger.warn((e as FirebaseError).message);\n } else {\n // `getToken()` should never throw, but logging error text to console will aid debugging.\n logger.error(e);\n }\n // Always save error to be added to dummy token.\n error = e as FirebaseError;\n }\n\n let interopTokenResult: AppCheckTokenResult | undefined;\n if (!token) {\n // If token is undefined, there must be an error.\n // Return a dummy token along with the error.\n interopTokenResult = makeDummyTokenResult(error!);\n } else if (error) {\n if (isValid(token)) {\n // It's also possible a valid token exists, but there's also an error.\n // (Such as if the token is almost expired, tries to refresh, and\n // the exchange request fails.)\n // We add a special error property here so that the refresher will\n // count this as a failed attempt and use the backoff instead of\n // retrying repeatedly with no delay, but any 3P listeners will not\n // be hindered in getting the still-valid token.\n interopTokenResult = {\n token: token.token,\n internalError: error\n };\n } else {\n // No invalid tokens should make it to this step. Memory and cached tokens\n // are checked. Other tokens are from fresh exchanges. But just in case.\n interopTokenResult = makeDummyTokenResult(error!);\n }\n } else {\n interopTokenResult = {\n token: token.token\n };\n // write the new token to the memory state as well as the persistent storage.\n // Only do it if we got a valid new token\n state.token = token;\n await writeTokenToStorage(app, token);\n }\n\n if (shouldCallListeners) {\n notifyTokenListeners(app, interopTokenResult);\n }\n return interopTokenResult;\n}\n\nexport function addTokenListener(\n appCheck: AppCheckService,\n type: ListenerType,\n listener: AppCheckTokenListener,\n onError?: (error: Error) => void\n): void {\n const { app } = appCheck;\n const state = getStateReference(app);\n const tokenObserver: AppCheckTokenObserver = {\n next: listener,\n error: onError,\n type\n };\n state.tokenObservers = [...state.tokenObservers, tokenObserver];\n\n // Invoke the listener async immediately if there is a valid token\n // in memory.\n if (state.token && isValid(state.token)) {\n const validToken = state.token;\n Promise.resolve()\n .then(() => {\n listener({ token: validToken.token });\n initTokenRefresher(appCheck);\n })\n .catch(() => {\n /* we don't care about exceptions thrown in listeners */\n });\n }\n\n /**\n * Wait for any cached token promise to resolve before starting the token\n * refresher. The refresher checks to see if there is an existing token\n * in state and calls the exchange endpoint if not. We should first let the\n * IndexedDB check have a chance to populate state if it can.\n *\n * Listener call isn't needed here because cachedTokenPromise will call any\n * listeners that exist when it resolves.\n */\n\n // state.cachedTokenPromise is always populated in `activate()`.\n void state.cachedTokenPromise!.then(() => initTokenRefresher(appCheck));\n}\n\nexport function removeTokenListener(\n app: FirebaseApp,\n listener: AppCheckTokenListener\n): void {\n const state = getStateReference(app);\n\n const newObservers = state.tokenObservers.filter(\n tokenObserver => tokenObserver.next !== listener\n );\n if (\n newObservers.length === 0 &&\n state.tokenRefresher &&\n state.tokenRefresher.isRunning()\n ) {\n state.tokenRefresher.stop();\n }\n\n state.tokenObservers = newObservers;\n}\n\n/**\n * Logic to create and start refresher as needed.\n */\nfunction initTokenRefresher(appCheck: AppCheckService): void {\n const { app } = appCheck;\n const state = getStateReference(app);\n // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n // is not true.\n let refresher: Refresher | undefined = state.tokenRefresher;\n if (!refresher) {\n refresher = createTokenRefresher(appCheck);\n state.tokenRefresher = refresher;\n }\n if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n refresher.start();\n }\n}\n\nfunction createTokenRefresher(appCheck: AppCheckService): Refresher {\n const { app } = appCheck;\n return new Refresher(\n // Keep in mind when this fails for any reason other than the ones\n // for which we should retry, it will effectively stop the proactive refresh.\n async () => {\n const state = getStateReference(app);\n // If there is no token, we will try to load it from storage and use it\n // If there is a token, we force refresh it because we know it's going to expire soon\n let result;\n if (!state.token) {\n result = await getToken(appCheck);\n } else {\n result = await getToken(appCheck, true);\n }\n\n /**\n * getToken() always resolves. In case the result has an error field defined, it means\n * the operation failed, and we should retry.\n */\n if (result.error) {\n throw result.error;\n }\n /**\n * A special `internalError` field reflects that there was an error\n * getting a new token from the exchange endpoint, but there's still a\n * previous token that's valid for now and this should be passed to 2P/3P\n * requests for a token. But we want this callback (`this.operation` in\n * `Refresher`) to throw in order to kick off the Refresher's retry\n * backoff. (Setting `hasSucceeded` to false.)\n */\n if (result.internalError) {\n throw result.internalError;\n }\n },\n () => {\n return true;\n },\n () => {\n const state = getStateReference(app);\n\n if (state.token) {\n // issuedAtTime + (50% * total TTL) + 5 minutes\n let nextRefreshTimeMillis =\n state.token.issuedAtTimeMillis +\n (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) *\n 0.5 +\n 5 * 60 * 1000;\n // Do not allow refresh time to be past (expireTime - 5 minutes)\n const latestAllowableRefresh =\n state.token.expireTimeMillis - 5 * 60 * 1000;\n nextRefreshTimeMillis = Math.min(\n nextRefreshTimeMillis,\n latestAllowableRefresh\n );\n return Math.max(0, nextRefreshTimeMillis - Date.now());\n } else {\n return 0;\n }\n },\n TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,\n TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT\n );\n}\n\nexport function notifyTokenListeners(\n app: FirebaseApp,\n token: AppCheckTokenResult\n): void {\n const observers = getStateReference(app).tokenObservers;\n\n for (const observer of observers) {\n try {\n if (observer.type === ListenerType.EXTERNAL && token.error != null) {\n // If this listener was added by a 3P call, send any token error to\n // the supplied error handler. A 3P observer always has an error\n // handler.\n observer.error!(token.error);\n } else {\n // If the token has no error field, always return the token.\n // If this is a 2P listener, return the token, whether or not it\n // has an error field.\n observer.next(token);\n }\n } catch (e) {\n // Errors in the listener function itself are always ignored.\n }\n }\n}\n\nexport function isValid(token: AppCheckTokenInternal): boolean {\n return token.expireTimeMillis - Date.now() > 0;\n}\n\nfunction makeDummyTokenResult(error: Error): AppCheckTokenResult {\n return {\n token: formatDummyToken(defaultTokenErrorData),\n error\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheck } from './public-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { FirebaseAppCheckInternal, ListenerType } from './types';\nimport {\n getToken,\n addTokenListener,\n removeTokenListener\n} from './internal-api';\nimport { Provider } from '@firebase/component';\nimport { getStateReference } from './state';\n\n/**\n * AppCheck Service class.\n */\nexport class AppCheckService implements AppCheck, _FirebaseService {\n constructor(\n public app: FirebaseApp,\n public heartbeatServiceProvider: Provider<'heartbeat'>\n ) {}\n _delete(): Promise<void> {\n const { tokenObservers } = getStateReference(this.app);\n for (const tokenObserver of tokenObservers) {\n removeTokenListener(this.app, tokenObserver.next);\n }\n return Promise.resolve();\n }\n}\n\nexport function factory(\n app: FirebaseApp,\n heartbeatServiceProvider: Provider<'heartbeat'>\n): AppCheckService {\n return new AppCheckService(app, heartbeatServiceProvider);\n}\n\nexport function internalFactory(\n appCheck: AppCheckService\n): FirebaseAppCheckInternal {\n return {\n getToken: forceRefresh => getToken(appCheck, forceRefresh),\n addTokenListener: listener =>\n addTokenListener(appCheck, ListenerType.INTERNAL, listener),\n removeTokenListener: listener => removeTokenListener(appCheck.app, listener)\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { getStateReference } from './state';\nimport { Deferred } from '@firebase/util';\nimport { getRecaptcha, ensureActivated } from './util';\n\nexport const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js';\nexport const RECAPTCHA_ENTERPRISE_URL =\n 'https://www.google.com/recaptcha/enterprise.js';\n\nexport function initializeV3(\n app: FirebaseApp,\n siteKey: string\n): Promise<GreCAPTCHA> {\n const initialized = new Deferred<GreCAPTCHA>();\n\n const state = getStateReference(app);\n state.reCAPTCHAState = { initialized };\n\n const divId = makeDiv(app);\n\n const grecaptcha = getRecaptcha(false);\n if (!grecaptcha) {\n loadReCAPTCHAV3Script(() => {\n const grecaptcha = getRecaptcha(false);\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n });\n } else {\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n }\n return initialized.promise;\n}\nexport function initializeEnterprise(\n app: FirebaseApp,\n siteKey: string\n): Promise<GreCAPTCHA> {\n const initialized = new Deferred<GreCAPTCHA>();\n\n const state = getStateReference(app);\n state.reCAPTCHAState = { initialized };\n\n const divId = makeDiv(app);\n\n const grecaptcha = getRecaptcha(true);\n if (!grecaptcha) {\n loadReCAPTCHAEnterpriseScript(() => {\n const grecaptcha = getRecaptcha(true);\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n });\n } else {\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n }\n return initialized.promise;\n}\n\n/**\n * Add listener to render the widget and resolve the promise when\n * the grecaptcha.ready() event fires.\n */\nfunction queueWidgetRender(\n app: FirebaseApp,\n siteKey: string,\n grecaptcha: GreCAPTCHA,\n container: string,\n initialized: Deferred<GreCAPTCHA>\n): void {\n grecaptcha.ready(() => {\n // Invisible widgets allow us to set a different siteKey for each widget,\n // so we use them to support multiple apps\n renderInvisibleWidget(app, siteKey, grecaptcha, container);\n initialized.resolve(grecaptcha);\n });\n}\n\n/**\n * Add invisible div to page.\n */\nfunction makeDiv(app: FirebaseApp): string {\n const divId = `fire_app_check_${app.name}`;\n const invisibleDiv = document.createElement('div');\n invisibleDiv.id = divId;\n invisibleDiv.style.display = 'none';\n\n document.body.appendChild(invisibleDiv);\n return divId;\n}\n\nexport async function getToken(app: FirebaseApp): Promise<string> {\n ensureActivated(app);\n\n // ensureActivated() guarantees that reCAPTCHAState is set\n const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n const recaptcha = await reCAPTCHAState.initialized.promise;\n\n return new Promise((resolve, _reject) => {\n // Updated after initialization is complete.\n const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n recaptcha.ready(() => {\n resolve(\n // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.\n recaptcha.execute(reCAPTCHAState.widgetId!, {\n action: 'fire_app_check'\n })\n );\n });\n });\n}\n\n/**\n *\n * @param app\n * @param container - Id of a HTML element.\n */\nfunction renderInvisibleWidget(\n app: FirebaseApp,\n siteKey: string,\n grecaptcha: GreCAPTCHA,\n container: string\n): void {\n const widgetId = grecaptcha.render(container, {\n sitekey: siteKey,\n size: 'invisible'\n });\n const state = getStateReference(app);\n\n state.reCAPTCHAState = {\n ...state.reCAPTCHAState!, // state.reCAPTCHAState is set in the initialize()\n widgetId\n };\n}\n\nfunction loadReCAPTCHAV3Script(onload: () => void): void {\n const script = document.createElement('script');\n script.src = RECAPTCHA_URL;\n script.onload = onload;\n document.head.appendChild(script);\n}\n\nfunction loadReCAPTCHAEnterpriseScript(onload: () => void): void {\n const script = document.createElement('script');\n script.src = RECAPTCHA_ENTERPRISE_URL;\n script.onload = onload;\n document.head.appendChild(script);\n}\n\ndeclare global {\n interface Window {\n grecaptcha: GreCAPTCHATopLevel | undefined;\n }\n}\n\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _getProvider } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n FirebaseError,\n issuedAtTime,\n calculateBackoffMillis\n} from '@firebase/util';\nimport {\n exchangeToken,\n getExchangeRecaptchaEnterpriseTokenRequest,\n getExchangeRecaptchaV3TokenRequest\n} from './client';\nimport { ONE_DAY } from './constants';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n getToken as getReCAPTCHAToken,\n initializeV3 as initializeRecaptchaV3,\n initializeEnterprise as initializeRecaptchaEnterprise\n} from './recaptcha';\nimport { AppCheckProvider, AppCheckTokenInternal, ThrottleData } from './types';\nimport { getDurationString } from './util';\n\n/**\n * App Check provider that can obtain a reCAPTCHA V3 token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaV3Provider implements AppCheckProvider {\n private _app?: FirebaseApp;\n private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n /**\n * Throttle requests on certain error codes to prevent too many retries\n * in a short time.\n */\n private _throttleData: ThrottleData | null = null;\n /**\n * Create a ReCaptchaV3Provider instance.\n * @param siteKey - ReCAPTCHA V3 siteKey.\n */\n constructor(private _siteKey: string) {}\n\n /**\n * Returns an App Check token.\n * @internal\n */\n async getToken(): Promise<AppCheckTokenInternal> {\n throwIfThrottled(this._throttleData);\n\n // Top-level `getToken()` has already checked that App Check is initialized\n // and therefore this._app and this._heartbeatServiceProvider are available.\n const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n _e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n );\n let result;\n try {\n result = await exchangeToken(\n getExchangeRecaptchaV3TokenRequest(this._app!, attestedClaimsToken),\n this._heartbeatServiceProvider!\n );\n } catch (e) {\n if (\n (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n ) {\n this._throttleData = setBackoff(\n Number((e as FirebaseError).customData?.httpStatus),\n this._throttleData\n );\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(\n this._throttleData.allowRequestsAfter - Date.now()\n ),\n httpStatus: this._throttleData.httpStatus\n });\n } else {\n throw e;\n }\n }\n // If successful, clear throttle data.\n this._throttleData = null;\n return result;\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n initializeRecaptchaV3(app, this._siteKey).catch(() => {\n /* we don't care about the initialization result */\n });\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof ReCaptchaV3Provider) {\n return this._siteKey === otherProvider._siteKey;\n } else {\n return false;\n }\n }\n}\n\n/**\n * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaEnterpriseProvider implements AppCheckProvider {\n private _app?: FirebaseApp;\n private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n /**\n * Throttle requests on certain error codes to prevent too many retries\n * in a short time.\n */\n private _throttleData: ThrottleData | null = null;\n /**\n * Create a ReCaptchaEnterpriseProvider instance.\n * @param siteKey - reCAPTCHA Enterprise score-based site key.\n */\n constructor(private _siteKey: string) {}\n\n /**\n * Returns an App Check token.\n * @internal\n */\n async getToken(): Promise<AppCheckTokenInternal> {\n throwIfThrottled(this._throttleData);\n // Top-level `getToken()` has already checked that App Check is initialized\n // and therefore this._app and this._heartbeatServiceProvider are available.\n const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n _e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n );\n let result;\n try {\n result = await exchangeToken(\n getExchangeRecaptchaEnterpriseTokenRequest(\n this._app!,\n attestedClaimsToken\n ),\n this._heartbeatServiceProvider!\n );\n } catch (e) {\n if (\n (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n ) {\n this._throttleData = setBackoff(\n Number((e as FirebaseError).customData?.httpStatus),\n this._throttleData\n );\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(\n this._throttleData.allowRequestsAfter - Date.now()\n ),\n httpStatus: this._throttleData.httpStatus\n });\n } else {\n throw e;\n }\n }\n // If successful, clear throttle data.\n this._throttleData = null;\n return result;\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n initializeRecaptchaEnterprise(app, this._siteKey).catch(() => {\n /* we don't care about the initialization result */\n });\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof ReCaptchaEnterpriseProvider) {\n return this._siteKey === otherProvider._siteKey;\n } else {\n return false;\n }\n }\n}\n\n/**\n * Custom provider class.\n * @public\n */\nexport class CustomProvider implements AppCheckProvider {\n private _app?: FirebaseApp;\n\n constructor(private _customProviderOptions: CustomProviderOptions) {}\n\n /**\n * @internal\n */\n async getToken(): Promise<AppCheckTokenInternal> {\n // custom provider\n const customToken = await this._customProviderOptions.getToken();\n // Try to extract IAT from custom token, in case this token is not\n // being newly issued. JWT timestamps are in seconds since epoch.\n const issuedAtTimeSeconds = issuedAtTime(customToken.token);\n // Very basic validation, use current timestamp as IAT if JWT\n // has no `iat` field or value is out of bounds.\n const issuedAtTimeMillis =\n issuedAtTimeSeconds !== null &&\n issuedAtTimeSeconds < Date.now() &&\n issuedAtTimeSeconds > 0\n ? issuedAtTimeSeconds * 1000\n : Date.now();\n\n return { ...customToken, issuedAtTimeMillis };\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof CustomProvider) {\n return (\n this._customProviderOptions.getToken.toString() ===\n otherProvider._customProviderOptions.getToken.toString()\n );\n } else {\n return false;\n }\n }\n}\n\n/**\n * Set throttle data to block requests until after a certain time\n * depending on the failed request's status code.\n * @param httpStatus - Status code of failed request.\n * @param throttleData - `ThrottleData` object containing previous throttle\n * data state.\n * @returns Data about current throttle state and expiration time.\n */\nfunction setBackoff(\n httpStatus: number,\n throttleData: ThrottleData | null\n): ThrottleData {\n /**\n * Block retries for 1 day for the following error codes:\n *\n * 404: Likely malformed URL.\n *\n * 403:\n * - Attestation failed\n * - Wrong API key\n * - Project deleted\n */\n if (httpStatus === 404 || httpStatus === 403) {\n return {\n backoffCount: 1,\n allowRequestsAfter: Date.now() + ONE_DAY,\n httpStatus\n };\n } else {\n /**\n * For all other error codes, the time when it is ok to retry again\n * is based on exponential backoff.\n */\n const backoffCount = throttleData ? throttleData.backoffCount : 0;\n const backoffMillis = calculateBackoffMillis(backoffCount, 1000, 2);\n return {\n backoffCount: backoffCount + 1,\n allowRequestsAfter: Date.now() + backoffMillis,\n httpStatus\n };\n }\n}\n\nfunction throwIfThrottled(throttleData: ThrottleData | null): void {\n if (throttleData) {\n if (Date.now() - throttleData.allowRequestsAfter <= 0) {\n // If before, throw.\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(throttleData.allowRequestsAfter - Date.now()),\n httpStatus: throttleData.httpStatus\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheck,\n AppCheckOptions,\n AppCheckTokenResult,\n Unsubscribe,\n PartialObserver\n} from './public-types';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport {\n getStateReference,\n getDebugState,\n DEFAULT_STATE,\n setInitialState\n} from './state';\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { getModularInstance, ErrorFn, NextFn } from '@firebase/util';\nimport { AppCheckService } from './factory';\nimport { AppCheckProvider, ListenerType } from './types';\nimport {\n getToken as getTokenInternal,\n addTokenListener,\n removeTokenListener,\n isValid,\n notifyTokenListeners\n} from './internal-api';\nimport { readTokenFromStorage } from './storage';\nimport { getDebugToken, initializeDebugMode, isDebugMode } from './debug';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'app-check': AppCheckService;\n }\n}\n\nexport {\n ReCaptchaV3Provider,\n CustomProvider,\n ReCaptchaEnterpriseProvider\n} from './providers';\n\n/**\n * Activate App Check for the given app. Can be called only once per app.\n * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for\n * @param options - App Check initialization options\n * @public\n */\nexport function initializeAppCheck(\n app: FirebaseApp = getApp(),\n options: AppCheckOptions\n): AppCheck {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'app-check');\n\n // Ensure initializeDebugMode() is only called once.\n if (!getDebugState().initialized) {\n initializeDebugMode();\n }\n\n // Log a message containing the debug token when `initializeAppCheck()`\n // is called in debug mode.\n if (isDebugMode()) {\n // Do not block initialization to get the token for the message.\n void getDebugToken().then(token =>\n // Not using logger because I don't think we ever want this accidentally hidden.\n console.log(\n `App Check debug token: ${token}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`\n )\n );\n }\n\n if (provider.isInitialized()) {\n const existingInstance = provider.getImmediate();\n const initialOptions = provider.getOptions() as unknown as AppCheckOptions;\n if (\n initialOptions.isTokenAutoRefreshEnabled ===\n options.isTokenAutoRefreshEnabled &&\n initialOptions.provider.isEqual(options.provider)\n ) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AppCheckError.ALREADY_INITIALIZED, {\n appName: app.name\n });\n }\n }\n\n const appCheck = provider.initialize({ options });\n _activate(app, options.provider, options.isTokenAutoRefreshEnabled);\n // If isTokenAutoRefreshEnabled is false, do not send any requests to the\n // exchange endpoint without an explicit call from the user either directly\n // or through another Firebase library (storage, functions, etc.)\n if (getStateReference(app).isTokenAutoRefreshEnabled) {\n // Adding a listener will start the refresher and fetch a token if needed.\n // This gets a token ready and prevents a delay when an internal library\n // requests the token.\n // Listener function does not need to do anything, its base functionality\n // of calling getToken() already fetches token and writes it to memory/storage.\n addTokenListener(appCheck, ListenerType.INTERNAL, () => {});\n }\n\n return appCheck;\n}\n\n/**\n * Activate App Check\n * @param app - Firebase app to activate App Check for.\n * @param provider - reCAPTCHA v3 provider or\n * custom token provider.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. If undefined, defaults to the\n * value of `app.automaticDataCollectionEnabled`, which defaults to\n * false and can be set in the app config.\n */\nfunction _activate(\n app: FirebaseApp,\n provider: AppCheckProvider,\n isTokenAutoRefreshEnabled?: boolean\n): void {\n // Create an entry in the APP_CHECK_STATES map. Further changes should\n // directly mutate this object.\n const state = setInitialState(app, { ...DEFAULT_STATE });\n\n state.activated = true;\n state.provider = provider; // Read cached token from storage if it exists and store it in memory.\n state.cachedTokenPromise = readTokenFromStorage(app).then(cachedToken => {\n if (cachedToken && isValid(cachedToken)) {\n state.token = cachedToken;\n // notify all listeners with the cached token\n notifyTokenListeners(app, { token: cachedToken.token });\n }\n return cachedToken;\n });\n\n // Use value of global `automaticDataCollectionEnabled` (which\n // itself defaults to false if not specified in config) if\n // `isTokenAutoRefreshEnabled` param was not provided by user.\n state.isTokenAutoRefreshEnabled =\n isTokenAutoRefreshEnabled === undefined\n ? app.automaticDataCollectionEnabled\n : isTokenAutoRefreshEnabled;\n\n state.provider.initialize(app);\n}\n\n/**\n * Set whether App Check will automatically refresh tokens as needed.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. This overrides any value set\n * during `initializeAppCheck()`.\n * @public\n */\nexport function setTokenAutoRefreshEnabled(\n appCheckInstance: AppCheck,\n isTokenAutoRefreshEnabled: boolean\n): void {\n const app = appCheckInstance.app;\n const state = getStateReference(app);\n // This will exist if any product libraries have called\n // `addTokenListener()`\n if (state.tokenRefresher) {\n if (isTokenAutoRefreshEnabled === true) {\n state.tokenRefresher.start();\n } else {\n state.tokenRefresher.stop();\n }\n }\n state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;\n}\n/**\n * Get the current App Check token. Attaches to the most recent\n * in-flight request if one is present. Returns null if no token\n * is present and no token requests are in-flight.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param forceRefresh - If true, will always try to fetch a fresh token.\n * If false, will use a cached token if found in storage.\n * @public\n */\nexport async function getToken(\n appCheckInstance: AppCheck,\n forceRefresh?: boolean\n): Promise<AppCheckTokenResult> {\n const result = await getTokenInternal(\n appCheckInstance as AppCheckService,\n forceRefresh\n );\n if (result.error) {\n throw result.error;\n }\n return { token: result.token };\n}\n\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param observer - An object with `next`, `error`, and `complete`\n * properties. `next` is called with an\n * {@link AppCheckTokenResult}\n * whenever the token changes. `error` is optional and is called if an\n * error is thrown by the listener (the `next` function). `complete`\n * is unused, as the token stream is unending.\n *\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n observer: PartialObserver<AppCheckTokenResult>\n): Unsubscribe;\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param onNext - When the token changes, this function is called with aa\n * {@link AppCheckTokenResult}.\n * @param onError - Optional. Called if there is an error thrown by the\n * listener (the `onNext` function).\n * @param onCompletion - Currently unused, as the token stream is unending.\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n onNext: (tokenResult: AppCheckTokenResult) => void,\n onError?: (error: Error) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Wraps `addTokenListener`/`removeTokenListener` methods in an `Observer`\n * pattern for public use.\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n onNextOrObserver:\n | ((tokenResult: AppCheckTokenResult) => void)\n | PartialObserver<AppCheckTokenResult>,\n onError?: (error: Error) => void,\n /**\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the token stream is never-ending.\n * It is added only for API consistency with the observer pattern, which\n * we follow in JS APIs.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onCompletion?: () => void\n): Unsubscribe {\n let nextFn: NextFn<AppCheckTokenResult> = () => {};\n let errorFn: ErrorFn = () => {};\n if ((onNextOrObserver as PartialObserver<AppCheckTokenResult>).next != null) {\n nextFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\n ).next!.bind(onNextOrObserver);\n } else {\n nextFn = onNextOrObserver as NextFn<AppCheckTokenResult>;\n }\n if (\n (onNextOrObserver as PartialObserver<AppCheckTokenResult>).error != null\n ) {\n errorFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\n ).error!.bind(onNextOrObserver);\n } else if (onError) {\n errorFn = onError;\n }\n addTokenListener(\n appCheckInstance as AppCheckService,\n ListenerType.EXTERNAL,\n nextFn,\n errorFn\n );\n return () => removeTokenListener(appCheckInstance.app, nextFn);\n}\n","/**\n * Firebase App Check\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\nimport { _AppCheckComponentName } from './public-types';\nimport { factory, internalFactory } from './factory';\nimport { _AppCheckInternalComponentName } from './types';\nimport { name, version } from '../package.json';\n\n// Used by other Firebase packages.\nexport { _AppCheckInternalComponentName };\n\nexport * from './api';\nexport * from './public-types';\n\nconst APP_CHECK_NAME: _AppCheckComponentName = 'app-check';\nconst APP_CHECK_NAME_INTERNAL: _AppCheckInternalComponentName =\n 'app-check-internal';\nfunction registerAppCheck(): void {\n // The public interface\n _registerComponent(\n new Component(\n APP_CHECK_NAME,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const heartbeatServiceProvider = container.getProvider('heartbeat');\n return factory(app, heartbeatServiceProvider);\n },\n ComponentType.PUBLIC\n )\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Initialize app-check-internal after app-check is initialized to make AppCheck available to\n * other Firebase SDKs\n */\n .setInstanceCreatedCallback(\n (container, _identifier, _appcheckService) => {\n container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();\n }\n )\n );\n\n // The internal interface used by other Firebase products\n _registerComponent(\n new Component(\n APP_CHECK_NAME_INTERNAL,\n container => {\n const appCheck = container.getProvider('app-check').getImmediate();\n return internalFactory(appCheck);\n },\n ComponentType.PUBLIC\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version);\n}\n\nregisterAppCheck();\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n USE_BEFORE_ACTIVATION = 'use-before-activation'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n [AppCheckError.USE_BEFORE_ACTIVATION]:\n 'App Check is being used before activate() is called for FirebaseApp {$appName}. ' +\n 'Call activate() before instantiating other Firebase services.'\n};\n\ninterface ErrorParams {\n [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n 'appCheck',\n 'AppCheck',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckProvider,\n AppCheckTokenResult,\n FirebaseAppCheck\n} from '@firebase/app-check-types';\nimport { _FirebaseService, FirebaseApp } from '@firebase/app-compat';\nimport {\n AppCheck as AppCheckServiceExp,\n CustomProvider,\n initializeAppCheck,\n ReCaptchaV3Provider,\n ReCaptchaEnterpriseProvider,\n setTokenAutoRefreshEnabled as setTokenAutoRefreshEnabledExp,\n getToken as getTokenExp,\n onTokenChanged as onTokenChangedExp\n} from '@firebase/app-check';\nimport { PartialObserver, Unsubscribe } from '@firebase/util';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\n\nexport class AppCheckService\n implements FirebaseAppCheck, Omit<_FirebaseService, '_delegate'>\n{\n _delegate?: AppCheckServiceExp;\n constructor(public app: FirebaseApp) {}\n\n activate(\n siteKeyOrProvider: string | AppCheckProvider,\n isTokenAutoRefreshEnabled?: boolean\n ): void {\n let provider:\n | ReCaptchaV3Provider\n | CustomProvider\n | ReCaptchaEnterpriseProvider;\n if (typeof siteKeyOrProvider === 'string') {\n provider = new ReCaptchaV3Provider(siteKeyOrProvider);\n } else if (\n siteKeyOrProvider instanceof ReCaptchaEnterpriseProvider ||\n siteKeyOrProvider instanceof ReCaptchaV3Provider ||\n siteKeyOrProvider instanceof CustomProvider\n ) {\n provider = siteKeyOrProvider;\n } else {\n provider = new CustomProvider({ getToken: siteKeyOrProvider.getToken });\n }\n this._delegate = initializeAppCheck(this.app, {\n provider,\n isTokenAutoRefreshEnabled\n });\n }\n\n setTokenAutoRefreshEnabled(isTokenAutoRefreshEnabled: boolean): void {\n if (!this._delegate) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: this.app.name\n });\n }\n setTokenAutoRefreshEnabledExp(this._delegate, isTokenAutoRefreshEnabled);\n }\n\n getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult> {\n if (!this._delegate) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: this.app.name\n });\n }\n return getTokenExp(this._delegate, forceRefresh);\n }\n\n onTokenChanged(\n onNextOrObserver:\n | PartialObserver<AppCheckTokenResult>\n | ((tokenResult: AppCheckTokenResult) => void),\n onError?: (error: Error) => void,\n onCompletion?: () => void\n ): Unsubscribe {\n if (!this._delegate) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: this.app.name\n });\n }\n return onTokenChangedExp(\n this._delegate,\n /**\n * Exp onTokenChanged() will handle both overloads but we need\n * to specify one to not confuse Typescript.\n */\n onNextOrObserver as (tokenResult: AppCheckTokenResult) => void,\n onError,\n onCompletion\n );\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, {\n _FirebaseNamespace,\n FirebaseApp\n} from '@firebase/app-compat';\nimport { name, version } from '../package.json';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport { AppCheckService } from './service';\nimport { FirebaseAppCheck } from '@firebase/app-check-types';\nimport {\n ReCaptchaV3Provider,\n ReCaptchaEnterpriseProvider,\n CustomProvider\n} from '@firebase/app-check';\n\nconst factory: InstanceFactory<'appCheck-compat'> = (\n container: ComponentContainer\n) => {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n\n return new AppCheckService(app as FirebaseApp);\n};\n\nexport function registerAppCheck(): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'appCheck-compat',\n factory,\n ComponentType.PUBLIC\n ).setServiceProps({\n ReCaptchaEnterpriseProvider,\n ReCaptchaV3Provider,\n CustomProvider\n })\n );\n}\n\nregisterAppCheck();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerAppCheck`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n appCheck(app?: FirebaseApp): FirebaseAppCheck;\n }\n interface FirebaseApp {\n appCheck(): FirebaseAppCheck;\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nexport const FactorId = {\n /** Phone as second factor */\n PHONE: 'phone'\n} as const;\n\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nexport const ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nexport const SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nexport const OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n} as const;\n\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nexport const ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_IDP_RESPONSE = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized'\n}\n\nfunction _debugErrorMap(): ErrorMap<AuthErrorCode> {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_IDP_RESPONSE]:\n 'The supplied auth credential is malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap<AuthErrorCode>;\n}\n\nfunction _prodErrorMap(): ErrorMap<AuthErrorCode> {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap<AuthErrorCode>;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams<K> = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName<K extends AuthErrorCode> = Omit<AuthErrorParams[K], 'appName'>;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams<K>;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams<K>)\n );\n}\n\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record<string, TypeExpectation | Optional> {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit<IArguments, 'callee'>,\n ...expected: Array<TypeExpectation | Optional>\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record<string, unknown>;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator<T> {\n new (): T;\n}\n\nconst instanceCache: Map<unknown, unknown> = new Map();\n\nexport function _getInstance<T>(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator<T>)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap<ApiError extends string> = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial<ServerErrorMap<ServerError>> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary<T extends { tenantId?: string }>(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest<T, V>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling<V>(\n auth: Auth,\n customErrorMap: Partial<ServerErrorMap<ServerError>>,\n fetchFn: () => Promise<Response>\n): Promise<V> {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout<Response>(auth);\n const response: Response = await Promise.race<Promise<Response>>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED);\n }\n}\n\nexport async function _performSignInRequest<T, V extends IdTokenResponse>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n const serverResponse = (await _performApiRequest<T, V | IdTokenMfaResponse>(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nclass NetworkTimeout<T> {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise<T>((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise<string> {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise<IdTokenResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated<T>(\n user: UserInternal,\n promise: Promise<T>,\n bypassAuthState = false\n): Promise<T> {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise<void> {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise<void> {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial<UserInternal> = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise<void> {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nfunction extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise<void> {\n return _performApiRequest<DeleteAccountRequest, void>(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise<DeleteLinkedAccountsResponse> {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise<GetAccountInfoResponse> {\n return _performApiRequest<GetAccountInfoRequest, GetAccountInfoResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise<string | null> {\n _assert(\n !this.accessToken || this.refreshToken,\n auth,\n AuthErrorCode.TOKEN_EXPIRED\n );\n\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise<void> {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n HttpMethod,\n HttpHeader\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum Endpoint {\n TOKEN = '/v1/token'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise<RequestStsTokenResponse> {\n const response =\n await _performFetchWithErrorHandling<RequestStsTokenServerResponse>(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\n\nimport {\n APIUserInfo,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert } from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise<string> {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise<IdTokenResult> {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise<void> {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn<APIUserInfo> | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n return new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n }\n\n _onReload(callback: NextFn<APIUserInfo>): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise<void> {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise<void> {\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserInternal> {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record<string, PersistenceValue> = {};\n\n async _isAvailable(): Promise<boolean> {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage[key] = value;\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise<void> {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise<void> {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise<UserInternal | null> {\n const blob = await this.persistence._get<PersistedBlob>(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise<void> {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise<void> {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise<void> {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise<PersistenceUserManager> {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance<PersistenceInternal>(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get<PersistedBlob>(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise<void>;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise<void> {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseService, FirebaseApp } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport { _assert } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport { AuthMiddlewareQueue } from './middleware';\n\ninterface AsyncAction {\n (): Promise<void>;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription<User>(this);\n private idTokenSubscription = new Subscription<User>(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise<void> | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory<AuthErrorCode, AuthErrorParams> =\n _DEFAULT_AUTH_ERROR_FACTORY;\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise<void> {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise<UserCredential | null> {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [<other queue tasks>] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise<void> {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise<void> {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise<void> {\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise<void> {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise<void> {\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise<void> {\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<PersistenceUserManager> {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise<UserInternal | null> {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise<void> {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription<User>,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => cb(this.currentUser));\n\n if (typeof nextOrObserver === 'function') {\n return subscription.addObserver(nextOrObserver, error, completed);\n } else {\n return subscription.addObserver(nextOrObserver);\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise<void> {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise<void> {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise<Record<string, string>> {\n // Additional headers on every request\n const headers: Record<string, string> = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n return headers;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription<T> {\n private observer: Observer<T | null> | null = null;\n readonly addObserver: Subscribe<T | null> = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn<T | null> {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise<ResetPasswordResponse> {\n return _performApiRequest<ResetPasswordRequest, ResetPasswordResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise<UpdateEmailPasswordResponse> {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise<ApplyActionCodeResponse> {\n return _performApiRequest<ApplyActionCodeRequest, ApplyActionCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise<SignInWithPasswordResponse> {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise<GetOobCodeResponse> {\n return _performApiRequest<GetOobCodeRequest, GetOobCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise<VerifyEmailResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise<PasswordResetResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise<EmailSignInResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise<VerifyAndChangeEmailResponse> {\n return sendOobCode(auth, request);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { updateEmailPassword } from '../../api/account_management/email_and_password';\nimport { signInWithPassword } from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n return signInWithPassword(auth, {\n returnSecureToken: true,\n email: this._email,\n password: this._password\n });\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n return updateEmailPassword(auth, {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password\n });\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return this._getIdTokenResponse(auth);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise<SignInWithIdpResponse> {\n return _performSignInRequest<SignInWithIdpRequest, SignInWithIdpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record<string, string> = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise<SendPhoneVerificationCodeResponse> {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap<ServerError>\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record<string, string> = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record<string, string>;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit<OAuthCredentialParams, 'signInMethod' | 'providerId'>\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\n/**\n * @public\n */\nexport class SAMLAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n providerId: string,\n private readonly pendingToken: string\n ) {\n super(providerId, providerId);\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): SAMLAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, pendingToken }: Record<string, string> =\n obj;\n if (\n !providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod\n ) {\n return null;\n }\n\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId: string, pendingToken: string): SAMLAuthCredential {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredential } from '../../model/public_types';\nimport { UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { SAMLAuthCredential } from '../credentials/saml';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { FederatedAuthProvider } from './federated';\n\nconst SAML_PROVIDER_PREFIX = 'saml.';\n\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nexport class SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId: string) {\n _assert(\n providerId.startsWith(SAML_PROVIDER_PREFIX),\n AuthErrorCode.ARGUMENT_ERROR\n );\n super(providerId);\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: string | object): AuthCredential {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, AuthErrorCode.ARGUMENT_ERROR);\n return credential;\n }\n\n private static samlCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): SAMLAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { pendingToken, providerId } = tokenResponse as SignInWithIdpResponse;\n\n if (!pendingToken || !providerId) {\n return null;\n }\n\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performSignInRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserCredentialInternal> {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise<UserCredentialImpl> {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise<IdTokenResponse> {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ProviderAssociatedObject {\n providerId?: string;\n}\n\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nexport function providerDataAsNames<T extends ProviderAssociatedObject>(\n providerData: T[]\n): Set<string> {\n return new Set(\n providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid) as string[]\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise<User> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialInternal> {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise<void> {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialImpl> {\n const { auth } = user;\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredential> {\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\n\nimport { signInWithCustomToken as getIdTokenResponse } from '../../api/authentication/custom_token';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nexport async function signInWithCustomToken(\n auth: Auth,\n customToken: string\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n const response: IdTokenResponse = await getIdTokenResponse(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(cred.user);\n return cred;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithCustomTokenRequest {\n token: string;\n returnSecureToken: boolean;\n tenantId?: string;\n}\n\nexport interface SignInWithCustomTokenResponse extends IdTokenResponse {}\n\nexport async function signInWithCustomToken(\n auth: Auth,\n request: SignInWithCustomTokenRequest\n): Promise<SignInWithCustomTokenResponse> {\n return _performSignInRequest<\n SignInWithCustomTokenRequest,\n SignInWithCustomTokenResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FactorId,\n MultiFactorInfo,\n PhoneMultiFactorInfo\n} from '../model/public_types';\nimport {\n PhoneMfaEnrollment,\n MfaEnrollment\n} from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _fail } from '../core/util/assert';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorInfoImpl implements MultiFactorInfo {\n readonly uid: string;\n readonly displayName?: string | null;\n readonly enrollmentTime: string;\n\n protected constructor(readonly factorId: FactorId, response: MfaEnrollment) {\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n\n static _fromServerResponse(\n auth: AuthInternal,\n enrollment: MfaEnrollment\n ): MultiFactorInfoImpl {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n}\n\nexport class PhoneMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements PhoneMultiFactorInfo\n{\n readonly phoneNumber: string;\n\n private constructor(response: PhoneMfaEnrollment) {\n super(FactorId.PHONE, response);\n this.phoneNumber = response.phoneInfo;\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): PhoneMultiFactorInfoImpl {\n return new PhoneMultiFactorInfoImpl(enrollment);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeSettings, Auth } from '../../model/public_types';\n\nimport { GetOobCodeRequest } from '../../api/authentication/email_and_password';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\nexport function _setActionCodeSettingsOnRequest(\n auth: Auth,\n request: GetOobCodeRequest,\n actionCodeSettings: ActionCodeSettings\n): void {\n _assert(\n actionCodeSettings.url?.length > 0,\n auth,\n AuthErrorCode.INVALID_CONTINUE_URI\n );\n _assert(\n typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0,\n auth,\n AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN\n );\n\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n\n if (actionCodeSettings.iOS) {\n _assert(\n actionCodeSettings.iOS.bundleId.length > 0,\n auth,\n AuthErrorCode.MISSING_IOS_BUNDLE_ID\n );\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n\n if (actionCodeSettings.android) {\n _assert(\n actionCodeSettings.android.packageName.length > 0,\n auth,\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME\n );\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _assert } from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Sends a password reset email to the given email address.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise<void> {\n const authModular = getModularInstance(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\n }\n\n await authentication.sendPasswordResetEmail(authModular, request);\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise<void> {\n await account.resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise<void> {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise<ActionCodeInfo> {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise<string> {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n const response = await signUp(authInternal, {\n returnSecureToken: true,\n email,\n password\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as api from '../../api/authentication/email_and_password';\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthProvider } from '../providers/email';\nimport { _getCurrentUrl } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n email: string,\n actionCodeSettings: ActionCodeSettings\n): Promise<void> {\n const authModular = getModularInstance(auth);\n const request: api.EmailSignInRequest = {\n requestType: ActionCodeOperation.EMAIL_SIGNIN,\n email\n };\n _assert(\n actionCodeSettings.handleCodeInApp,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\n }\n\n await api.sendSignInLinkToEmail(authModular, request);\n}\n\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport function isSignInWithEmailLink(auth: Auth, emailLink: string): boolean {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === ActionCodeOperation.EMAIL_SIGNIN;\n}\n\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport async function signInWithEmailLink(\n auth: Auth,\n email: string,\n emailLink?: string\n): Promise<UserCredential> {\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(\n email,\n emailLink || _getCurrentUrl()\n );\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(\n credential._tenantId === (authModular.tenantId || null),\n authModular,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n return signInWithCredential(authModular, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n User\n} from '../../model/public_types';\n\nimport {\n createAuthUri,\n CreateAuthUriRequest\n} from '../../api/authentication/create_auth_uri';\nimport * as api from '../../api/authentication/email_and_password';\nimport { UserInternal } from '../../model/user';\nimport { _getCurrentUrl, _isHttpOrHttps } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Gets the list of possible sign in methods for the given email address.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * @public\n */\nexport async function fetchSignInMethodsForEmail(\n auth: Auth,\n email: string\n): Promise<string[]> {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request: CreateAuthUriRequest = {\n identifier: email,\n continueUri\n };\n\n const { signinMethods } = await createAuthUri(\n getModularInstance(auth),\n request\n );\n\n return signinMethods || [];\n}\n\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendEmailVerification(\n user: User,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise<void> {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_EMAIL,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.sendEmailVerification(userInternal.auth, request);\n\n if (email !== user.email) {\n await user.reload();\n }\n}\n\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function verifyBeforeUpdateEmail(\n user: User,\n newEmail: string,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise<void> {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyAndChangeEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.verifyAndChangeEmail(userInternal.auth, request);\n\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface CreateAuthUriRequest {\n identifier: string;\n continueUri: string;\n tenantId?: string;\n}\n\nexport interface CreateAuthUriResponse {\n signinMethods: string[];\n}\n\nexport async function createAuthUri(\n auth: Auth,\n request: CreateAuthUriRequest\n): Promise<CreateAuthUriResponse> {\n return _performApiRequest<CreateAuthUriRequest, CreateAuthUriResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.CREATE_AUTH_URI,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport {\n updateEmailPassword as apiUpdateEmailPassword,\n UpdateEmailPasswordRequest\n} from '../../api/account_management/email_and_password';\nimport { updateProfile as apiUpdateProfile } from '../../api/account_management/profile';\nimport { UserInternal } from '../../model/user';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nexport async function updateProfile(\n user: User,\n {\n displayName,\n photoURL: photoUrl\n }: { displayName?: string | null; photoURL?: string | null }\n): Promise<void> {\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(\n userInternal,\n apiUpdateProfile(userInternal.auth, profileRequest)\n );\n\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(\n ({ providerId }) => providerId === ProviderId.PASSWORD\n );\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n\n await userInternal._updateTokensIfNecessary(response);\n}\n\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * @public\n */\nexport function updateEmail(user: User, newEmail: string): Promise<void> {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n newEmail,\n null\n );\n}\n\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport function updatePassword(user: User, newPassword: string): Promise<void> {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n null,\n newPassword\n );\n}\n\nasync function updateEmailOrPassword(\n user: UserInternal,\n email: string | null,\n password: string | null\n): Promise<void> {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request: UpdateEmailPasswordRequest = {\n idToken,\n returnSecureToken: true\n };\n\n if (email) {\n request.email = email;\n }\n\n if (password) {\n request.password = password;\n }\n\n const response = await _logoutIfInvalidated(\n user,\n apiUpdateEmailPassword(auth, request)\n );\n await user._updateTokensIfNecessary(response, /* reload */ true);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface UpdateProfileRequest {\n idToken: string;\n displayName?: string | null;\n photoUrl?: string | null;\n returnSecureToken: boolean;\n}\n\nexport interface UpdateProfileResponse extends IdTokenResponse {\n displayName?: string | null;\n photoUrl?: string | null;\n}\n\nexport async function updateProfile(\n auth: Auth,\n request: UpdateProfileRequest\n): Promise<UpdateProfileResponse> {\n return _performApiRequest<UpdateProfileRequest, UpdateProfileResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AdditionalUserInfo, UserCredential } from '../../model/public_types';\nimport { IdTokenResponse, IdTokenResponseKind } from '../../model/id_token';\nimport { _parseToken } from './id_token_result';\nimport { UserCredentialInternal } from '../../model/user';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nexport function _fromIdTokenResponse(\n idTokenResponse?: IdTokenResponse\n): AdditionalUserInfo | null {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser =\n idTokenResponse.isNewUser ||\n idTokenResponse.kind === IdTokenResponseKind.SignupNewUser;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.[\n 'sign_in_provider'\n ];\n if (signInProvider) {\n const filteredProviderId =\n signInProvider !== ProviderId.ANONYMOUS &&\n signInProvider !== ProviderId.CUSTOM\n ? (signInProvider as ProviderId)\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case ProviderId.FACEBOOK:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GITHUB:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GOOGLE:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case ProviderId.TWITTER:\n return new TwitterAdditionalUserInfo(\n isNewUser,\n profile,\n idTokenResponse.screenName || null\n );\n case ProviderId.CUSTOM:\n case ProviderId.ANONYMOUS:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\n\nclass GenericAdditionalUserInfo implements AdditionalUserInfo {\n constructor(\n readonly isNewUser: boolean,\n readonly providerId: ProviderId | string | null,\n readonly profile: Record<string, unknown> = {}\n ) {}\n}\n\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(\n isNewUser: boolean,\n providerId: ProviderId,\n profile: Record<string, unknown>,\n readonly username: string | null\n ) {\n super(isNewUser, providerId, profile);\n }\n}\n\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record<string, unknown>) {\n super(isNewUser, ProviderId.FACEBOOK, profile);\n }\n}\n\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser: boolean, profile: Record<string, unknown>) {\n super(\n isNewUser,\n ProviderId.GITHUB,\n profile,\n typeof profile?.login === 'string' ? profile?.login : null\n );\n }\n}\n\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record<string, unknown>) {\n super(isNewUser, ProviderId.GOOGLE, profile);\n }\n}\n\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(\n isNewUser: boolean,\n profile: Record<string, unknown>,\n screenName: string | null\n ) {\n super(isNewUser, ProviderId.TWITTER, profile, screenName);\n }\n}\n\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nexport function getAdditionalUserInfo(\n userCredential: UserCredential\n): AdditionalUserInfo | null {\n const { user, _tokenResponse } = userCredential as UserCredentialInternal;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n\n return _fromIdTokenResponse(_tokenResponse);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AuthInternal } from '../model/auth';\nimport { MultiFactorSession } from '../model/public_types';\n\nexport const enum MultiFactorSessionType {\n ENROLL = 'enroll',\n SIGN_IN = 'signin'\n}\n\ninterface SerializedMultiFactorSession {\n multiFactorSession: {\n idToken?: string;\n pendingCredential?: string;\n };\n}\n\nexport class MultiFactorSessionImpl implements MultiFactorSession {\n private constructor(\n readonly type: MultiFactorSessionType,\n readonly credential: string,\n readonly auth?: AuthInternal\n ) {}\n\n static _fromIdtoken(\n idToken: string,\n auth?: AuthInternal\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.ENROLL,\n idToken,\n auth\n );\n }\n\n static _fromMfaPendingCredential(\n mfaPendingCredential: string\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.SIGN_IN,\n mfaPendingCredential\n );\n }\n\n toJSON(): SerializedMultiFactorSession {\n const key =\n this.type === MultiFactorSessionType.ENROLL\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n\n static fromJSON(\n obj: Partial<SerializedMultiFactorSession>\n ): MultiFactorSessionImpl | null {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(\n obj.multiFactorSession.pendingCredential\n );\n } else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(\n obj.multiFactorSession.idToken\n );\n }\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n MultiFactorResolver,\n UserCredential,\n MultiFactorError\n} from '../model/public_types';\n\nimport { _castAuth } from '../core/auth/auth_impl';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserCredentialImpl } from '../core/user/user_credential_impl';\nimport { _assert, _fail } from '../core/util/assert';\nimport { UserCredentialInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorError as MultiFactorErrorInternal } from './mfa_error';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../model/enums';\n\nexport class MultiFactorResolverImpl implements MultiFactorResolver {\n private constructor(\n readonly session: MultiFactorSessionImpl,\n readonly hints: MultiFactorInfoImpl[],\n private readonly signInResolver: (\n assertion: MultiFactorAssertionImpl\n ) => Promise<UserCredentialInternal>\n ) {}\n\n /** @internal */\n static _fromError(\n authExtern: Auth,\n error: MultiFactorErrorInternal\n ): MultiFactorResolverImpl {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(auth, enrollment)\n );\n\n _assert(\n serverResponse.mfaPendingCredential,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(\n serverResponse.mfaPendingCredential\n );\n\n return new MultiFactorResolverImpl(\n session,\n hints,\n async (\n assertion: MultiFactorAssertionImpl\n ): Promise<UserCredentialInternal> => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case OperationType.SIGN_IN:\n const userCredential =\n await UserCredentialImpl._fromIdTokenResponse(\n auth,\n error.operationType,\n idTokenResponse\n );\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case OperationType.REAUTHENTICATE:\n _assert(error.user, auth, AuthErrorCode.INTERNAL_ERROR);\n return UserCredentialImpl._forOperation(\n error.user,\n error.operationType,\n idTokenResponse\n );\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n );\n }\n\n async resolveSignIn(\n assertionExtern: MultiFactorAssertionImpl\n ): Promise<UserCredential> {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n return this.signInResolver(assertion);\n }\n}\n\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nexport function getMultiFactorResolver(\n auth: Auth,\n error: MultiFactorError\n): MultiFactorResolver {\n const authModular = getModularInstance(auth);\n const errorInternal = error as MultiFactorErrorInternal;\n _assert(\n error.customData.operationType,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n errorInternal.customData._serverResponse?.mfaPendingCredential,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise<MultiFactorSession> {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user.auth\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise<void> {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise<void> {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n try {\n await this.user.reload();\n } catch (e) {\n if (\n (e as FirebaseError)?.code !== `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n ) {\n throw e;\n }\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap<User, MultiFactorUser>();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment is supported\n */\nexport type MfaEnrollment = PhoneMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise<StartPhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise<FinalizePhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise<WithdrawMfaResponse> {\n return _performApiRequest<WithdrawMfaRequest, WithdrawMfaResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record<string, unknown>;\n\nexport interface Instantiator<T> {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise<boolean>;\n _set(key: string, value: PersistenceValue): Promise<void>;\n _get<T extends PersistenceValue>(key: string): Promise<T | null>;\n _remove(key: string): Promise<void>;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise<boolean> {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise<void> {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, string | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = await super._get<T>(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise<void> {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set<ReceiverHandler<any, any>>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise<void> {\n const messageEvent = event as MessageEvent<SenderMessageEvent<S>>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set<ReceiverHandler<T, S>> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler: ReceiverHandler<T, S>\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler?: ReceiverHandler<T, S>\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult<T> {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult<T> =\n | PromiseFulfilledResult<T>\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled<T>(\n promises: Array<Promise<T>>\n): Promise<Array<PromiseSettledResult<T>>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult<T>;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\n }\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set<MessageHandler>();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse<T>> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse<T>>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent<ReceiverMessageEvent<T>>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent<S>,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Recaptcha } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record<string, any>;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise<ServiceWorker | null> {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\n *\n */\nclass DBPromise<T> {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise<void> {\n const objectStore = getObjectStore(db, true);\n return new DBPromise<void>(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise<void> {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport function _openDatabase(): Promise<IDBDatabase> {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise<void> {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise<void>(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise<PersistedBlob | null> {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise<DBObject | undefined>(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise<void> {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, PersistenceValue | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise<void>;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise<IDBDatabase> {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries<T>(op: (db: IDBDatabase) => Promise<T>): Promise<T> {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise<void> {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise<void> {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise<void> {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise<void> {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send<KeyChangedResponse, KeyChangedRequest>(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise<boolean> {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise<void>): Promise<void> {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise<string[]> {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise<DBObject[] | null>(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\nimport { _createError } from '../core/util/assert';\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\nexport function _loadJS(url: string): Promise<Event> {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record<string, unknown>;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport { RecaptchaParameters } from '../../model/public_types';\nimport { Recaptcha } from './recaptcha';\n\nexport const _SOLVE_TIME_MS = 500;\nexport const _EXPIRATION_TIME_MS = 60_000;\nexport const _WIDGET_ID_START = 1_000_000_000_000;\n\nexport interface Widget {\n getResponse: () => string | null;\n delete: () => void;\n execute: () => void;\n}\n\nexport class MockReCaptcha implements Recaptcha {\n private counter = _WIDGET_ID_START;\n _widgets = new Map<number, Widget>();\n\n constructor(private readonly auth: AuthInternal) {}\n\n render(\n container: string | HTMLElement,\n parameters?: RecaptchaParameters\n ): number {\n const id = this.counter;\n this._widgets.set(\n id,\n new MockWidget(container, this.auth.name, parameters || {})\n );\n this.counter++;\n return id;\n }\n\n reset(optWidgetId?: number): void {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n\n getResponse(optWidgetId?: number): string {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n\n async execute(optWidgetId?: number | string): Promise<string> {\n const id: number = (optWidgetId as number) || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\n\nexport class MockWidget {\n private readonly container: HTMLElement;\n private readonly isVisible: boolean;\n private timerId: number | null = null;\n private deleted = false;\n private responseToken: string | null = null;\n private readonly clickHandler = (): void => {\n this.execute();\n };\n\n constructor(\n containerOrId: string | HTMLElement,\n appName: string,\n private readonly params: RecaptchaParameters\n ) {\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, AuthErrorCode.ARGUMENT_ERROR, { appName });\n\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n } else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n\n getResponse(): string | null {\n this.checkIfDeleted();\n return this.responseToken;\n }\n\n delete(): void {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n\n execute(): void {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n } catch (e) {}\n }\n\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n } catch (e) {}\n }\n\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n\n private checkIfDeleted(): void {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\n\nfunction generateRandomAlphaNumericString(len: number): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(\n allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))\n );\n }\n return chars.join('');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise<Recaptcha>;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise<Recaptcha> {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl)) {\n return Promise.resolve(_window().grecaptcha!);\n }\n return new Promise<Recaptcha>((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha;\n\n if (!recaptcha) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${RECAPTCHA_BASE}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise<Recaptcha> {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set<TokenCallback>();\n private renderPromise: Promise<number> | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n */\n constructor(\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n },\n authExtern: Auth\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise<string> {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise<string>(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise<number> {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise<number> {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise<void> {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise<void> {\n let resolver: (() => void) | null = null;\n return new Promise<void>(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise<string> {\n return (\n (\n await _performApiRequest<void, GetRecaptchaParamResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise<UserCredential>;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise<UserCredential> {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise<string> {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise<void> {\n await _link(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise<StartPhoneMfaSignInResponse> {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise<FinalizePhoneMfaSignInResponse> {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise<string> {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise<UserCredentialInternal>;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise<UserCredentialInternal>;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise<void>;\n\n execute(): Promise<UserCredentialInternal | null> {\n return new Promise<UserCredentialInternal | null>(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay.\n */\nexport const enum _Timeout {\n AUTH_EVENT = 2000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise<UserCredential> {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise<void> {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise<UserCredentialInternal | null>\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise<UserCredentialInternal | null> {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise<void> {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<boolean> {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<void> {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise<UserCredentialInternal | null>\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport { _assertInstanceOf } from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link signInWithRedirect}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _signInWithRedirect(auth, provider, resolver) as Promise<never>;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link reauthenticateWithRedirect}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise<never>;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link linkWithRedirect}.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _linkWithRedirect(user, provider, resolver) as Promise<never>;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential | null> {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise<UserCredential | null> {\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise<string> {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set<string> = new Set();\n private readonly consumers: Set<AuthEventConsumer> = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise<GetProjectConfigResponse> {\n return _performApiRequest<GetProjectConfigRequest, GetProjectConfigResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise<void> {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n return new Promise<gapi.iframes.Context>((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise<gapi.iframes.Context> | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record<string, string> = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise<gapi.iframes.Iframe> {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\n });\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record<string, string>\n): string {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record<string, string | number>;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record<string, boolean>;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise<EventManager>;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record<string, ManagerOrPromise> = {};\n private readonly iframes: Record<string, gapi.iframes.Iframe> = {};\n private readonly originValidationPromises: Record<string, Promise<void>> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<AuthPopup> {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<never> {\n await this._originValidation(auth);\n _setWindowLocation(\n _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)\n );\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise<EventManager> {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise<EventManager> {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register<GapiAuthEvent>(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send<gapi.iframes.Message, WebStorageSupportMessage>(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise<void> {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n FactorId,\n PhoneMultiFactorAssertion\n} from '../../../model/public_types';\n\nimport { MultiFactorAssertionImpl } from '../../../mfa/mfa_assertion';\nimport { AuthInternal } from '../../../model/auth';\nimport { finalizeEnrollPhoneMfa } from '../../../api/account_management/mfa';\nimport { PhoneAuthCredential } from '../../../core/credentials/phone';\nimport {\n finalizeSignInPhoneMfa,\n FinalizeMfaResponse\n} from '../../../api/authentication/mfa';\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nexport class PhoneMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements PhoneMultiFactorAssertion\n{\n private constructor(private readonly credential: PhoneAuthCredential) {\n super(FactorId.PHONE);\n }\n\n /** @internal */\n static _fromCredential(\n credential: PhoneAuthCredential\n ): PhoneMultiFactorAssertionImpl {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n\n /** @internal */\n _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise<FinalizeMfaResponse> {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise<FinalizeMfaResponse> {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nexport class PhoneMultiFactorGenerator {\n private constructor() {}\n\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n\n /**\n * The identifier of the phone second factor: `phone`.\n */\n static FACTOR_ID = 'phone';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FactorId, MultiFactorAssertion } from '../model/public_types';\nimport { debugFail } from '../core/util/assert';\nimport { MultiFactorSessionImpl, MultiFactorSessionType } from './mfa_session';\nimport { FinalizeMfaResponse } from '../api/authentication/mfa';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorAssertionImpl implements MultiFactorAssertion {\n protected constructor(readonly factorId: FactorId) {}\n\n _process(\n auth: AuthInternal,\n session: MultiFactorSessionImpl,\n displayName?: string | null\n ): Promise<FinalizeMfaResponse> {\n switch (session.type) {\n case MultiFactorSessionType.ENROLL:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case MultiFactorSessionType.SIGN_IN:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n\n abstract _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise<FinalizeMfaResponse>;\n abstract _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise<FinalizeMfaResponse>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map<TokenListener, Unsubscribe> =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\n if (authTokenSyncUrl) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nregisterAuth(ClientPlatform.BROWSER);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const { apiKey, authDomain } = app.options;\n return ((app, heartbeatServiceProvider) => {\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n // Auth domain is optional if IdP sign in isn't being used\n _assert(!authDomain?.includes(':'), AuthErrorCode.ARGUMENT_ERROR, {\n appName: app.name\n });\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n })(app, heartbeatServiceProvider);\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface CordovaWindow extends Window {\n cordova: {\n plugins: {\n browsertab: {\n isAvailable(cb: (available: boolean) => void): void;\n openUrl(url: string): void;\n close(): void;\n };\n };\n\n InAppBrowser: {\n open(url: string, target: string, options: string): InAppBrowserRef;\n };\n };\n\n universalLinks: {\n subscribe(\n n: null,\n cb: (event: Record<string, string> | null) => void\n ): void;\n };\n\n BuildInfo: {\n readonly packageName: string;\n readonly displayName: string;\n };\n\n handleOpenURL(url: string): void;\n}\n\nexport interface InAppBrowserRef {\n close?: () => void;\n}\n\nexport function _cordovaWindow(): CordovaWindow {\n return window as unknown as CordovaWindow;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map<PersistenceInternal>(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n debugAssert,\n _assert,\n _createError,\n _fail\n} from '../../core/util/assert';\nimport { _isAndroid, _isIOS, _isIOS7Or8 } from '../../core/util/browser';\nimport { _getRedirectUrl } from '../../core/util/handler';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthEvent } from '../../model/popup_redirect';\nimport { InAppBrowserRef, _cordovaWindow } from '../plugins';\nimport {\n GetProjectConfigRequest,\n _getProjectConfig\n} from '../../api/project_config/get_project_config';\n\n/**\n * How long to wait after the app comes back into focus before concluding that\n * the user closed the sign in tab.\n */\nconst REDIRECT_TIMEOUT_MS = 2000;\n\n/**\n * Generates the URL for the OAuth handler.\n */\nexport async function _generateHandlerUrl(\n auth: AuthInternal,\n event: AuthEvent,\n provider: AuthProvider\n): Promise<string> {\n // Get the cordova plugins\n const { BuildInfo } = _cordovaWindow();\n debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');\n const sessionDigest = await computeSha256(event.sessionId);\n\n const additionalParams: Record<string, string> = {};\n if (_isIOS()) {\n // iOS app identifier\n additionalParams['ibi'] = BuildInfo.packageName;\n } else if (_isAndroid()) {\n // Android app identifier\n additionalParams['apn'] = BuildInfo.packageName;\n } else {\n _fail(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED);\n }\n\n // Add the display name if available\n if (BuildInfo.displayName) {\n additionalParams['appDisplayName'] = BuildInfo.displayName;\n }\n\n // Attached the hashed session ID\n additionalParams['sessionId'] = sessionDigest;\n return _getRedirectUrl(\n auth,\n provider,\n event.type,\n undefined,\n event.eventId ?? undefined,\n additionalParams\n );\n}\n\n/**\n * Validates that this app is valid for this project configuration\n */\nexport async function _validateOrigin(auth: AuthInternal): Promise<void> {\n const { BuildInfo } = _cordovaWindow();\n const request: GetProjectConfigRequest = {};\n if (_isIOS()) {\n request.iosBundleId = BuildInfo.packageName;\n } else if (_isAndroid()) {\n request.androidPackageName = BuildInfo.packageName;\n } else {\n _fail(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED);\n }\n\n // Will fail automatically if package name is not authorized\n await _getProjectConfig(auth, request);\n}\n\nexport function _performRedirect(\n handlerUrl: string\n): Promise<InAppBrowserRef | null> {\n // Get the cordova plugins\n const { cordova } = _cordovaWindow();\n\n return new Promise(resolve => {\n cordova.plugins.browsertab.isAvailable(browserTabIsAvailable => {\n let iabRef: InAppBrowserRef | null = null;\n if (browserTabIsAvailable) {\n cordova.plugins.browsertab.openUrl(handlerUrl);\n } else {\n // TODO: Return the inappbrowser ref that's returned from the open call\n iabRef = cordova.InAppBrowser.open(\n handlerUrl,\n _isIOS7Or8() ? '_blank' : '_system',\n 'location=yes'\n );\n }\n resolve(iabRef);\n });\n });\n}\n\n// Thin interface wrapper to avoid circular dependency with ./events module\ninterface PassiveAuthEventListener {\n addPassiveListener(cb: () => void): void;\n removePassiveListener(cb: () => void): void;\n}\n\n/**\n * This function waits for app activity to be seen before resolving. It does\n * this by attaching listeners to various dom events. Once the app is determined\n * to be visible, this promise resolves. AFTER that resolution, the listeners\n * are detached and any browser tabs left open will be closed.\n */\nexport async function _waitForAppResume(\n auth: AuthInternal,\n eventListener: PassiveAuthEventListener,\n iabRef: InAppBrowserRef | null\n): Promise<void> {\n // Get the cordova plugins\n const { cordova } = _cordovaWindow();\n\n let cleanup = (): void => {};\n try {\n await new Promise<void>((resolve, reject) => {\n let onCloseTimer: number | null = null;\n\n // DEFINE ALL THE CALLBACKS =====\n function authEventSeen(): void {\n // Auth event was detected. Resolve this promise and close the extra\n // window if it's still open.\n resolve();\n const closeBrowserTab = cordova.plugins.browsertab?.close;\n if (typeof closeBrowserTab === 'function') {\n closeBrowserTab();\n }\n // Close inappbrowser emebedded webview in iOS7 and 8 case if still\n // open.\n if (typeof iabRef?.close === 'function') {\n iabRef.close();\n }\n }\n\n function resumed(): void {\n if (onCloseTimer) {\n // This code already ran; do not rerun.\n return;\n }\n\n onCloseTimer = window.setTimeout(() => {\n // Wait two seeconds after resume then reject.\n reject(_createError(auth, AuthErrorCode.REDIRECT_CANCELLED_BY_USER));\n }, REDIRECT_TIMEOUT_MS);\n }\n\n function visibilityChanged(): void {\n if (document?.visibilityState === 'visible') {\n resumed();\n }\n }\n\n // ATTACH ALL THE LISTENERS =====\n // Listen for the auth event\n eventListener.addPassiveListener(authEventSeen);\n\n // Listen for resume and visibility events\n document.addEventListener('resume', resumed, false);\n if (_isAndroid()) {\n document.addEventListener('visibilitychange', visibilityChanged, false);\n }\n\n // SETUP THE CLEANUP FUNCTION =====\n cleanup = () => {\n eventListener.removePassiveListener(authEventSeen);\n document.removeEventListener('resume', resumed, false);\n document.removeEventListener(\n 'visibilitychange',\n visibilityChanged,\n false\n );\n if (onCloseTimer) {\n window.clearTimeout(onCloseTimer);\n }\n };\n });\n } finally {\n cleanup();\n }\n}\n\n/**\n * Checks the configuration of the Cordova environment. This has no side effect\n * if the configuration is correct; otherwise it throws an error with the\n * missing plugin.\n */\nexport function _checkCordovaConfiguration(auth: AuthInternal): void {\n const win = _cordovaWindow();\n // Check all dependencies installed.\n // https://github.com/nordnet/cordova-universal-links-plugin\n // Note that cordova-universal-links-plugin has been abandoned.\n // A fork with latest fixes is available at:\n // https://www.npmjs.com/package/cordova-universal-links-plugin-fix\n _assert(\n typeof win?.universalLinks?.subscribe === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-universal-links-plugin-fix'\n }\n );\n\n // https://www.npmjs.com/package/cordova-plugin-buildinfo\n _assert(\n typeof win?.BuildInfo?.packageName !== 'undefined',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-buildInfo'\n }\n );\n\n // https://github.com/google/cordova-plugin-browsertab\n _assert(\n typeof win?.cordova?.plugins?.browsertab?.openUrl === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-browsertab'\n }\n );\n _assert(\n typeof win?.cordova?.plugins?.browsertab?.isAvailable === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-browsertab'\n }\n );\n\n // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/\n _assert(\n typeof win?.cordova?.InAppBrowser?.open === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-inappbrowser'\n }\n );\n}\n\n/**\n * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only\n * available in \"secure\" contexts, which covers Cordova (which is served on a file\n * protocol).\n */\nasync function computeSha256(sessionId: string): Promise<string> {\n const bytes = stringToArrayBuffer(sessionId);\n\n // TODO: For IE11 crypto has a different name and this operation comes back\n // as an object, not a promise. This is the old proposed standard that\n // is used by IE11:\n // https://www.w3.org/TR/2013/WD-WebCryptoAPI-20130108/#cryptooperation-interface\n const buf = await crypto.subtle.digest('SHA-256', bytes);\n const arr = Array.from(new Uint8Array(buf));\n return arr.map(num => num.toString(16).padStart(2, '0')).join('');\n}\n\nfunction stringToArrayBuffer(str: string): Uint8Array {\n // This function is only meant to deal with an ASCII charset and makes\n // certain simplifying assumptions.\n debugAssert(\n /[0-9a-zA-Z]+/.test(str),\n 'Can only convert alpha-numeric strings'\n );\n if (typeof TextEncoder !== 'undefined') {\n return new TextEncoder().encode(str);\n }\n\n const buff = new ArrayBuffer(str.length);\n const view = new Uint8Array(buff);\n for (let i = 0; i < str.length; i++) {\n view[i] = str.charCodeAt(i);\n }\n return view;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystringDecode } from '@firebase/util';\nimport { AuthEventManager } from '../../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../../core/errors';\nimport { PersistedBlob, PersistenceInternal } from '../../core/persistence';\nimport {\n KeyName,\n _persistenceKeyName\n} from '../../core/persistence/persistence_user_manager';\nimport { _createError } from '../../core/util/assert';\nimport { _getInstance } from '../../core/util/instantiator';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthEvent, AuthEventType } from '../../model/popup_redirect';\nimport { browserLocalPersistence } from '../../platform_browser/persistence/local_storage';\n\nconst SESSION_ID_LENGTH = 20;\n\n/** Custom AuthEventManager that adds passive listeners to events */\nexport class CordovaAuthEventManager extends AuthEventManager {\n private readonly passiveListeners = new Set<(e: AuthEvent) => void>();\n private resolveInialized!: () => void;\n private initPromise = new Promise<void>(resolve => {\n this.resolveInialized = resolve;\n });\n\n addPassiveListener(cb: (e: AuthEvent) => void): void {\n this.passiveListeners.add(cb);\n }\n\n removePassiveListener(cb: (e: AuthEvent) => void): void {\n this.passiveListeners.delete(cb);\n }\n\n // In a Cordova environment, this manager can live through multiple redirect\n // operations\n resetRedirect(): void {\n this.queuedRedirectEvent = null;\n this.hasHandledPotentialRedirect = false;\n }\n\n /** Override the onEvent method */\n onEvent(event: AuthEvent): boolean {\n this.resolveInialized();\n this.passiveListeners.forEach(cb => cb(event));\n return super.onEvent(event);\n }\n\n async initialized(): Promise<void> {\n await this.initPromise;\n }\n}\n\n/**\n * Generates a (partial) {@link AuthEvent}.\n */\nexport function _generateNewEvent(\n auth: AuthInternal,\n type: AuthEventType,\n eventId: string | null = null\n): AuthEvent {\n return {\n type,\n eventId,\n urlResponse: null,\n sessionId: generateSessionId(),\n postBody: null,\n tenantId: auth.tenantId,\n error: _createError(auth, AuthErrorCode.NO_AUTH_EVENT)\n };\n}\n\nexport function _savePartialEvent(\n auth: AuthInternal,\n event: AuthEvent\n): Promise<void> {\n return storage()._set(persistenceKey(auth), event as object as PersistedBlob);\n}\n\nexport async function _getAndRemoveEvent(\n auth: AuthInternal\n): Promise<AuthEvent | null> {\n const event = (await storage()._get(\n persistenceKey(auth)\n )) as AuthEvent | null;\n if (event) {\n await storage()._remove(persistenceKey(auth));\n }\n return event;\n}\n\nexport function _eventFromPartialAndUrl(\n partialEvent: AuthEvent,\n url: string\n): AuthEvent | null {\n // Parse the deep link within the dynamic link URL.\n const callbackUrl = _getDeepLinkFromCallback(url);\n // Confirm it is actually a callback URL.\n // Currently the universal link will be of this format:\n // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>\n // This is a fake URL but is not intended to take the user anywhere\n // and just redirect to the app.\n if (callbackUrl.includes('/__/auth/callback')) {\n // Check if there is an error in the URL.\n // This mechanism is also used to pass errors back to the app:\n // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>\n const params = searchParamsOrEmpty(callbackUrl);\n // Get the error object corresponding to the stringified error if found.\n const errorObject = params['firebaseError']\n ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))\n : null;\n const code = errorObject?.['code']?.split('auth/')?.[1];\n const error = code ? _createError(code) : null;\n if (error) {\n return {\n type: partialEvent.type,\n eventId: partialEvent.eventId,\n tenantId: partialEvent.tenantId,\n error,\n urlResponse: null,\n sessionId: null,\n postBody: null\n };\n } else {\n return {\n type: partialEvent.type,\n eventId: partialEvent.eventId,\n tenantId: partialEvent.tenantId,\n sessionId: partialEvent.sessionId,\n urlResponse: callbackUrl,\n postBody: null\n };\n }\n }\n\n return null;\n}\n\nfunction generateSessionId(): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < SESSION_ID_LENGTH; i++) {\n const idx = Math.floor(Math.random() * allowedChars.length);\n chars.push(allowedChars.charAt(idx));\n }\n return chars.join('');\n}\n\nfunction storage(): PersistenceInternal {\n return _getInstance(browserLocalPersistence);\n}\n\nfunction persistenceKey(auth: AuthInternal): string {\n return _persistenceKeyName(KeyName.AUTH_EVENT, auth.config.apiKey, auth.name);\n}\n\nfunction parseJsonOrNull(json: string): ReturnType<typeof JSON.parse> | null {\n try {\n return JSON.parse(json);\n } catch (e) {\n return null;\n }\n}\n\n// Exported for testing\nexport function _getDeepLinkFromCallback(url: string): string {\n const params = searchParamsOrEmpty(url);\n const link = params['link'] ? decodeURIComponent(params['link']) : undefined;\n // Double link case (automatic redirect)\n const doubleDeepLink = searchParamsOrEmpty(link)['link'];\n // iOS custom scheme links.\n const iOSDeepLink = params['deep_link_id']\n ? decodeURIComponent(params['deep_link_id'])\n : undefined;\n const iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * Optimistically tries to get search params from a string, or else returns an\n * empty search params object.\n */\nfunction searchParamsOrEmpty(url: string | undefined): Record<string, string> {\n if (!url?.includes('?')) {\n return {};\n }\n\n const [_, ...rest] = url.split('?');\n return querystringDecode(rest.join('?')) as Record<string, string>;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../../model/public_types';\nimport { browserSessionPersistence } from '../../platform_browser/persistence/session_storage';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { AuthPopup } from '../../platform_browser/util/popup';\nimport { _createError, _fail } from '../../core/util/assert';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _checkCordovaConfiguration,\n _generateHandlerUrl,\n _performRedirect,\n _validateOrigin,\n _waitForAppResume\n} from './utils';\nimport {\n CordovaAuthEventManager,\n _eventFromPartialAndUrl,\n _generateNewEvent,\n _getAndRemoveEvent,\n _savePartialEvent\n} from './events';\nimport { AuthEventManager } from '../../core/auth/auth_event_manager';\nimport { _getRedirectResult } from '../../platform_browser/strategies/redirect';\nimport {\n _clearRedirectOutcomes,\n _overrideRedirectResult\n} from '../../core/strategies/redirect';\nimport { _cordovaWindow } from '../plugins';\n\n/**\n * How long to wait for the initial auth event before concluding no\n * redirect pending\n */\nconst INITIAL_EVENT_TIMEOUT_MS = 500;\n\nclass CordovaPopupRedirectResolver implements PopupRedirectResolverInternal {\n readonly _redirectPersistence = browserSessionPersistence;\n readonly _shouldInitProactively = true; // This is lightweight for Cordova\n private readonly eventManagers = new Map<string, CordovaAuthEventManager>();\n private readonly originValidationPromises: Record<string, Promise<void>> = {};\n\n _completeRedirectFn = _getRedirectResult;\n _overrideRedirectResult = _overrideRedirectResult;\n\n async _initialize(auth: AuthInternal): Promise<CordovaAuthEventManager> {\n const key = auth._key();\n let manager = this.eventManagers.get(key);\n if (!manager) {\n manager = new CordovaAuthEventManager(auth);\n this.eventManagers.set(key, manager);\n this.attachCallbackListeners(auth, manager);\n }\n return manager;\n }\n\n _openPopup(auth: AuthInternal): Promise<AuthPopup> {\n _fail(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED);\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<void> {\n _checkCordovaConfiguration(auth);\n const manager = await this._initialize(auth);\n await manager.initialized();\n\n // Reset the persisted redirect states. This does not matter on Web where\n // the redirect always blows away application state entirely. On Cordova,\n // the app maintains control flow through the redirect.\n manager.resetRedirect();\n _clearRedirectOutcomes();\n\n await this._originValidation(auth);\n\n const event = _generateNewEvent(auth, authType, eventId);\n await _savePartialEvent(auth, event);\n const url = await _generateHandlerUrl(auth, event, provider);\n const iabRef = await _performRedirect(url);\n return _waitForAppResume(auth, manager, iabRef);\n }\n\n _isIframeWebStorageSupported(\n _auth: AuthInternal,\n _cb: (support: boolean) => unknown\n ): void {\n throw new Error('Method not implemented.');\n }\n\n _originValidation(auth: AuthInternal): Promise<void> {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n private attachCallbackListeners(\n auth: AuthInternal,\n manager: AuthEventManager\n ): void {\n // Get the global plugins\n const { universalLinks, handleOpenURL, BuildInfo } = _cordovaWindow();\n\n const noEventTimeout = setTimeout(async () => {\n // We didn't see that initial event. Clear any pending object and\n // dispatch no event\n await _getAndRemoveEvent(auth);\n manager.onEvent(generateNoEvent());\n }, INITIAL_EVENT_TIMEOUT_MS);\n\n const universalLinksCb = async (\n eventData: Record<string, string> | null\n ): Promise<void> => {\n // We have an event so we can clear the no event timeout\n clearTimeout(noEventTimeout);\n\n const partialEvent = await _getAndRemoveEvent(auth);\n let finalEvent: AuthEvent | null = null;\n if (partialEvent && eventData?.['url']) {\n finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);\n }\n\n // If finalEvent is never filled, trigger with no event\n manager.onEvent(finalEvent || generateNoEvent());\n };\n\n // Universal links subscriber doesn't exist for iOS, so we need to check\n if (\n typeof universalLinks !== 'undefined' &&\n typeof universalLinks.subscribe === 'function'\n ) {\n universalLinks.subscribe(null, universalLinksCb);\n }\n\n // iOS 7 or 8 custom URL schemes.\n // This is also the current default behavior for iOS 9+.\n // For this to work, cordova-plugin-customurlscheme needs to be installed.\n // https://github.com/EddyVerbruggen/Custom-URL-scheme\n // Do not overwrite the existing developer's URL handler.\n const existingHandleOpenURL = handleOpenURL;\n const packagePrefix = `${BuildInfo.packageName.toLowerCase()}://`;\n _cordovaWindow().handleOpenURL = async url => {\n if (url.toLowerCase().startsWith(packagePrefix)) {\n // We want this intentionally to float\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n universalLinksCb({ url });\n }\n // Call the developer's handler if it is present.\n if (typeof existingHandleOpenURL === 'function') {\n try {\n existingHandleOpenURL(url);\n } catch (e) {\n // This is a developer error. Don't stop the flow of the SDK.\n console.error(e);\n }\n }\n };\n }\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for Cordova\n * based applications.\n *\n * @public\n */\nexport const cordovaPopupRedirectResolver: PopupRedirectResolver =\n CordovaPopupRedirectResolver;\n\nfunction generateNoEvent(): AuthEvent {\n return {\n type: AuthEventType.UNKNOWN,\n eventId: null,\n sessionId: null,\n urlResponse: null,\n postBody: null,\n tenantId: null,\n error: _createError(AuthErrorCode.NO_AUTH_EVENT)\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport * as impl from '@firebase/auth/internal';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\nimport { FirebaseError } from '@firebase/util';\n\nimport * as types from '@firebase/auth-types';\nimport { name, version } from './package.json';\nimport { Auth } from './src/auth';\nimport { PhoneAuthProvider as CompatAuthProvider } from './src/phone_auth_provider';\nimport { RecaptchaVerifier as CompatRecaptchaVerifier } from './src/recaptcha_verifier';\n\nconst AUTH_TYPE = 'auth-compat';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'auth-compat': types.FirebaseAuth;\n }\n}\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n auth: {\n (app?: FirebaseApp): types.FirebaseAuth;\n Auth: typeof types.FirebaseAuth;\n EmailAuthProvider: typeof types.EmailAuthProvider;\n EmailAuthProvider_Instance: typeof types.EmailAuthProvider_Instance;\n FacebookAuthProvider: typeof types.FacebookAuthProvider;\n FacebookAuthProvider_Instance: typeof types.FacebookAuthProvider_Instance;\n GithubAuthProvider: typeof types.GithubAuthProvider;\n GithubAuthProvider_Instance: typeof types.GithubAuthProvider_Instance;\n GoogleAuthProvider: typeof types.GoogleAuthProvider;\n GoogleAuthProvider_Instance: typeof types.GoogleAuthProvider_Instance;\n OAuthProvider: typeof types.OAuthProvider;\n SAMLAuthProvider: typeof types.SAMLAuthProvider;\n PhoneAuthProvider: typeof types.PhoneAuthProvider;\n PhoneAuthProvider_Instance: typeof types.PhoneAuthProvider_Instance;\n PhoneMultiFactorGenerator: typeof types.PhoneMultiFactorGenerator;\n RecaptchaVerifier: typeof types.RecaptchaVerifier;\n RecaptchaVerifier_Instance: typeof types.RecaptchaVerifier_Instance;\n TwitterAuthProvider: typeof types.TwitterAuthProvider;\n TwitterAuthProvider_Instance: typeof types.TwitterAuthProvider_Instance;\n };\n }\n interface FirebaseApp {\n auth?(): types.FirebaseAuth;\n }\n}\n\n// Create auth components to register with firebase.\n// Provides Auth public APIs.\nfunction registerAuthCompat(instance: _FirebaseNamespace): void {\n instance.INTERNAL.registerComponent(\n new Component(\n AUTH_TYPE,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const authProvider = container.getProvider('auth');\n return new Auth(app, authProvider);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps({\n ActionCodeInfo: {\n Operation: {\n EMAIL_SIGNIN: impl.ActionCodeOperation.EMAIL_SIGNIN,\n PASSWORD_RESET: impl.ActionCodeOperation.PASSWORD_RESET,\n RECOVER_EMAIL: impl.ActionCodeOperation.RECOVER_EMAIL,\n REVERT_SECOND_FACTOR_ADDITION:\n impl.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,\n VERIFY_AND_CHANGE_EMAIL:\n impl.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n VERIFY_EMAIL: impl.ActionCodeOperation.VERIFY_EMAIL\n }\n },\n EmailAuthProvider: impl.EmailAuthProvider,\n FacebookAuthProvider: impl.FacebookAuthProvider,\n GithubAuthProvider: impl.GithubAuthProvider,\n GoogleAuthProvider: impl.GoogleAuthProvider,\n OAuthProvider: impl.OAuthProvider,\n SAMLAuthProvider: impl.SAMLAuthProvider,\n PhoneAuthProvider: CompatAuthProvider,\n PhoneMultiFactorGenerator: impl.PhoneMultiFactorGenerator,\n RecaptchaVerifier: CompatRecaptchaVerifier,\n TwitterAuthProvider: impl.TwitterAuthProvider,\n Auth,\n AuthCredential: impl.AuthCredential,\n Error: FirebaseError\n })\n .setInstantiationMode(InstantiationMode.LAZY)\n .setMultipleInstances(false)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterAuthCompat(firebase as _FirebaseNamespace);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as impl from '@firebase/auth/internal';\nimport {\n getUA,\n isBrowserExtension,\n isReactNative,\n isNode,\n isIE,\n isIndexedDBAvailable\n} from '@firebase/util';\n\ndeclare global {\n interface Document {\n documentMode?: number;\n }\n}\n\nconst CORDOVA_ONDEVICEREADY_TIMEOUT_MS = 1000;\n\nfunction _getCurrentScheme(): string | null {\n return self?.location?.protocol || null;\n}\n\n/**\n * @return {boolean} Whether the current environment is http or https.\n */\nfunction _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\n/**\n * @param {?string=} ua The user agent.\n * @return {boolean} Whether the app is rendered in a mobile iOS or Android\n * Cordova environment.\n */\nexport function _isAndroidOrIosCordovaScheme(ua: string = getUA()): boolean {\n return !!(\n (_getCurrentScheme() === 'file:' ||\n _getCurrentScheme() === 'ionic:' ||\n _getCurrentScheme() === 'capacitor:') &&\n ua.toLowerCase().match(/iphone|ipad|ipod|android/)\n );\n}\n\n/**\n * @return {boolean} Whether the environment is a native environment, where\n * CORS checks do not apply.\n */\nfunction _isNativeEnvironment(): boolean {\n return isReactNative() || isNode();\n}\n\n/**\n * Checks whether the user agent is IE11.\n * @return {boolean} True if it is IE11.\n */\nfunction _isIe11(): boolean {\n return isIE() && document?.documentMode === 11;\n}\n\n/**\n * Checks whether the user agent is Edge.\n * @param {string} userAgent The browser user agent string.\n * @return {boolean} True if it is Edge.\n */\nfunction _isEdge(ua: string = getUA()): boolean {\n return /Edge\\/\\d+/.test(ua);\n}\n\n/**\n * @param {?string=} opt_userAgent The navigator user agent.\n * @return {boolean} Whether local storage is not synchronized between an iframe\n * and a popup of the same domain.\n */\nfunction _isLocalStorageNotSynchronized(ua: string = getUA()): boolean {\n return _isIe11() || _isEdge(ua);\n}\n\n/** @return {boolean} Whether web storage is supported. */\nexport function _isWebStorageSupported(): boolean {\n try {\n const storage = self.localStorage;\n const key = impl._generateEventId();\n if (storage) {\n // setItem will throw an exception if we cannot access WebStorage (e.g.,\n // Safari in private mode).\n storage['setItem'](key, '1');\n storage['removeItem'](key);\n // For browsers where iframe web storage does not synchronize with a popup\n // of the same domain, indexedDB is used for persistent storage. These\n // browsers include IE11 and Edge.\n // Make sure it is supported (IE11 and Edge private mode does not support\n // that).\n if (_isLocalStorageNotSynchronized()) {\n // In such browsers, if indexedDB is not supported, an iframe cannot be\n // notified of the popup sign in result.\n return isIndexedDBAvailable();\n }\n return true;\n }\n } catch (e) {\n // localStorage is not available from a worker. Test availability of\n // indexedDB.\n return _isWorker() && isIndexedDBAvailable();\n }\n return false;\n}\n\n/**\n * @param {?Object=} global The optional global scope.\n * @return {boolean} Whether current environment is a worker.\n */\nexport function _isWorker(): boolean {\n // WorkerGlobalScope only defined in worker environment.\n return (\n typeof global !== 'undefined' &&\n 'WorkerGlobalScope' in global &&\n 'importScripts' in global\n );\n}\n\nexport function _isPopupRedirectSupported(): boolean {\n return (\n (_isHttpOrHttps() ||\n isBrowserExtension() ||\n _isAndroidOrIosCordovaScheme()) &&\n // React Native with remote debugging reports its location.protocol as\n // http.\n !_isNativeEnvironment() &&\n // Local storage has to be supported for browser popup and redirect\n // operations to work.\n _isWebStorageSupported() &&\n // DOM, popups and redirects are not supported within a worker.\n !_isWorker()\n );\n}\n\n/** Quick check that indicates the platform *may* be Cordova */\nexport function _isLikelyCordova(): boolean {\n return _isAndroidOrIosCordovaScheme() && typeof document !== 'undefined';\n}\n\nexport async function _isCordova(): Promise<boolean> {\n if (!_isLikelyCordova()) {\n return false;\n }\n\n return new Promise(resolve => {\n const timeoutId = setTimeout(() => {\n // We've waited long enough; the telltale Cordova event didn't happen\n resolve(false);\n }, CORDOVA_ONDEVICEREADY_TIMEOUT_MS);\n\n document.addEventListener('deviceready', () => {\n clearTimeout(timeoutId);\n resolve(true);\n });\n });\n}\n\nexport function _getSelfWindow(): Window | null {\n return typeof window !== 'undefined' ? window : null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport { isIndexedDBAvailable, isNode, isReactNative } from '@firebase/util';\nimport { _getSelfWindow, _isWebStorageSupported, _isWorker } from './platform';\n\nexport const Persistence = {\n LOCAL: 'local',\n NONE: 'none',\n SESSION: 'session'\n};\n\nconst _assert: typeof exp._assert = exp._assert;\n\nconst PERSISTENCE_KEY = 'persistence';\n\n/**\n * Validates that an argument is a valid persistence value. If an invalid type\n * is specified, an error is thrown synchronously.\n */\nexport function _validatePersistenceArgument(\n auth: exp.Auth,\n persistence: string\n): void {\n _assert(\n Object.values(Persistence).includes(persistence),\n auth,\n exp.AuthErrorCode.INVALID_PERSISTENCE\n );\n // Validate if the specified type is supported in the current environment.\n if (isReactNative()) {\n // This is only supported in a browser.\n _assert(\n persistence !== Persistence.SESSION,\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n if (isNode()) {\n // Only none is supported in Node.js.\n _assert(\n persistence === Persistence.NONE,\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n if (_isWorker()) {\n // In a worker environment, either LOCAL or NONE are supported.\n // If indexedDB not supported and LOCAL provided, throw an error\n _assert(\n persistence === Persistence.NONE ||\n (persistence === Persistence.LOCAL && isIndexedDBAvailable()),\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n // This is restricted by what the browser supports.\n _assert(\n persistence === Persistence.NONE || _isWebStorageSupported(),\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n}\n\nexport async function _savePersistenceForRedirect(\n auth: exp.AuthInternal\n): Promise<void> {\n await auth._initializationPromise;\n const session = getSessionStorageIfAvailable();\n const key = exp._persistenceKeyName(\n PERSISTENCE_KEY,\n auth.config.apiKey,\n auth.name\n );\n if (session) {\n session.setItem(key, auth._getPersistence());\n }\n}\n\nexport function _getPersistencesFromRedirect(\n apiKey: string,\n appName: string\n): exp.Persistence[] {\n const session = getSessionStorageIfAvailable();\n if (!session) {\n return [];\n }\n\n const key = exp._persistenceKeyName(PERSISTENCE_KEY, apiKey, appName);\n const persistence = session.getItem(key);\n\n switch (persistence) {\n case Persistence.NONE:\n return [exp.inMemoryPersistence];\n case Persistence.LOCAL:\n return [exp.indexedDBLocalPersistence, exp.browserSessionPersistence];\n case Persistence.SESSION:\n return [exp.browserSessionPersistence];\n default:\n return [];\n }\n}\n\n/** Returns session storage, or null if the property access errors */\nfunction getSessionStorageIfAvailable(): Storage | null {\n try {\n return _getSelfWindow()?.sessionStorage || null;\n } catch (e) {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport { _isCordova, _isLikelyCordova } from './platform';\n\nconst _assert: typeof exp._assert = exp._assert;\n\n/** Platform-agnostic popup-redirect resolver */\nexport class CompatPopupRedirectResolver\n implements exp.PopupRedirectResolverInternal\n{\n // Create both resolvers for dynamic resolution later\n private readonly browserResolver: exp.PopupRedirectResolverInternal =\n exp._getInstance(exp.browserPopupRedirectResolver);\n private readonly cordovaResolver: exp.PopupRedirectResolverInternal =\n exp._getInstance(exp.cordovaPopupRedirectResolver);\n // The actual resolver in use: either browserResolver or cordovaResolver.\n private underlyingResolver: exp.PopupRedirectResolverInternal | null = null;\n _redirectPersistence = exp.browserSessionPersistence;\n\n _completeRedirectFn: (\n auth: exp.Auth,\n resolver: exp.PopupRedirectResolver,\n bypassAuthState: boolean\n ) => Promise<exp.UserCredential | null> = exp._getRedirectResult;\n _overrideRedirectResult = exp._overrideRedirectResult;\n\n async _initialize(auth: exp.AuthImpl): Promise<exp.EventManager> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._initialize(auth);\n }\n\n async _openPopup(\n auth: exp.AuthImpl,\n provider: exp.AuthProvider,\n authType: exp.AuthEventType,\n eventId?: string\n ): Promise<exp.AuthPopup> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._openPopup(\n auth,\n provider,\n authType,\n eventId\n );\n }\n\n async _openRedirect(\n auth: exp.AuthImpl,\n provider: exp.AuthProvider,\n authType: exp.AuthEventType,\n eventId?: string\n ): Promise<void> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._openRedirect(\n auth,\n provider,\n authType,\n eventId\n );\n }\n\n _isIframeWebStorageSupported(\n auth: exp.AuthImpl,\n cb: (support: boolean) => unknown\n ): void {\n this.assertedUnderlyingResolver._isIframeWebStorageSupported(auth, cb);\n }\n\n _originValidation(auth: exp.Auth): Promise<void> {\n return this.assertedUnderlyingResolver._originValidation(auth);\n }\n\n get _shouldInitProactively(): boolean {\n return _isLikelyCordova() || this.browserResolver._shouldInitProactively;\n }\n\n private get assertedUnderlyingResolver(): exp.PopupRedirectResolverInternal {\n _assert(this.underlyingResolver, exp.AuthErrorCode.INTERNAL_ERROR);\n return this.underlyingResolver;\n }\n\n private async selectUnderlyingResolver(): Promise<void> {\n if (this.underlyingResolver) {\n return;\n }\n\n // We haven't yet determined whether or not we're in Cordova; go ahead\n // and determine that state now.\n const isCordova = await _isCordova();\n this.underlyingResolver = isCordova\n ? this.cordovaResolver\n : this.browserResolver;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Forward direction wrapper from Compat --unwrap-> Exp */\nexport interface Wrapper<T> {\n unwrap(): T;\n}\n\n/** Reverse direction wrapper from Exp --wrapped--> Compat */\nexport interface ReverseWrapper<T> {\n wrapped(): T;\n}\n\nexport function unwrap<T>(object: unknown): T {\n return (object as Wrapper<T>).unwrap();\n}\n\nexport function wrapped<T>(object: unknown): T {\n return (object as ReverseWrapper<T>).wrapped();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { FirebaseError } from '@firebase/util';\nimport { Auth } from './auth';\nimport { User } from './user';\nimport { unwrap, wrapped } from './wrap';\n\nfunction credentialFromResponse(\n userCredential: exp.UserCredentialInternal\n): exp.AuthCredential | null {\n return credentialFromObject(userCredential);\n}\n\nfunction attachExtraErrorFields(auth: exp.Auth, e: FirebaseError): void {\n // The response contains all fields from the server which may or may not\n // actually match the underlying type\n const response = (e.customData as exp.TaggedWithTokenResponse | undefined)\n ?._tokenResponse as unknown as Record<string, string>;\n if ((e as FirebaseError)?.code === 'auth/multi-factor-auth-required') {\n const mfaErr = e as compat.MultiFactorError;\n mfaErr.resolver = new MultiFactorResolver(\n auth,\n exp.getMultiFactorResolver(auth, e as exp.MultiFactorError)\n );\n } else if (response) {\n const credential = credentialFromObject(e);\n const credErr = e as compat.AuthError;\n if (credential) {\n credErr.credential = credential;\n credErr.tenantId = response.tenantId || undefined;\n credErr.email = response.email || undefined;\n credErr.phoneNumber = response.phoneNumber || undefined;\n }\n }\n}\n\nfunction credentialFromObject(\n object: FirebaseError | exp.UserCredential\n): exp.AuthCredential | null {\n const { _tokenResponse } = (\n object instanceof FirebaseError ? object.customData : object\n ) as exp.TaggedWithTokenResponse;\n if (!_tokenResponse) {\n return null;\n }\n\n // Handle phone Auth credential responses, as they have a different format\n // from other backend responses (i.e. no providerId). This is also only the\n // case for user credentials (does not work for errors).\n if (!(object instanceof FirebaseError)) {\n if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {\n return exp.PhoneAuthProvider.credentialFromResult(object);\n }\n }\n\n const providerId = _tokenResponse.providerId;\n\n // Email and password is not supported as there is no situation where the\n // server would return the password to the client.\n if (!providerId || providerId === exp.ProviderId.PASSWORD) {\n return null;\n }\n\n let provider: Pick<\n typeof exp.OAuthProvider,\n 'credentialFromResult' | 'credentialFromError'\n >;\n switch (providerId) {\n case exp.ProviderId.GOOGLE:\n provider = exp.GoogleAuthProvider;\n break;\n case exp.ProviderId.FACEBOOK:\n provider = exp.FacebookAuthProvider;\n break;\n case exp.ProviderId.GITHUB:\n provider = exp.GithubAuthProvider;\n break;\n case exp.ProviderId.TWITTER:\n provider = exp.TwitterAuthProvider;\n break;\n default:\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce\n } = _tokenResponse as exp.SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n // TODO(avolkovi): uncomment this and get it working with SAML & OIDC\n if (pendingToken) {\n if (providerId.startsWith('saml.')) {\n return exp.SAMLAuthCredential._create(providerId, pendingToken);\n } else {\n // OIDC and non-default providers excluding Twitter.\n return exp.OAuthCredential._fromParams({\n providerId,\n signInMethod: providerId,\n pendingToken,\n idToken: oauthIdToken,\n accessToken: oauthAccessToken\n });\n }\n }\n return new exp.OAuthProvider(providerId).credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n rawNonce: nonce\n });\n }\n\n return object instanceof FirebaseError\n ? provider.credentialFromError(object)\n : provider.credentialFromResult(object);\n}\n\nexport function convertCredential(\n auth: exp.Auth,\n credentialPromise: Promise<exp.UserCredential>\n): Promise<compat.UserCredential> {\n return credentialPromise\n .catch(e => {\n if (e instanceof FirebaseError) {\n attachExtraErrorFields(auth, e);\n }\n throw e;\n })\n .then(credential => {\n const operationType = credential.operationType;\n const user = credential.user;\n\n return {\n operationType,\n credential: credentialFromResponse(\n credential as exp.UserCredentialInternal\n ),\n additionalUserInfo: exp.getAdditionalUserInfo(\n credential as exp.UserCredential\n ),\n user: User.getOrCreate(user)\n };\n });\n}\n\nexport async function convertConfirmationResult(\n auth: exp.Auth,\n confirmationResultPromise: Promise<exp.ConfirmationResult>\n): Promise<compat.ConfirmationResult> {\n const confirmationResultExp = await confirmationResultPromise;\n return {\n verificationId: confirmationResultExp.verificationId,\n confirm: (verificationCode: string) =>\n convertCredential(auth, confirmationResultExp.confirm(verificationCode))\n };\n}\n\nclass MultiFactorResolver implements compat.MultiFactorResolver {\n readonly auth: Auth;\n constructor(\n auth: exp.Auth,\n private readonly resolver: exp.MultiFactorResolver\n ) {\n this.auth = wrapped(auth);\n }\n\n get session(): compat.MultiFactorSession {\n return this.resolver.session;\n }\n\n get hints(): compat.MultiFactorInfo[] {\n return this.resolver.hints;\n }\n\n resolveSignIn(\n assertion: compat.MultiFactorAssertion\n ): Promise<compat.UserCredential> {\n return convertCredential(\n unwrap(this.auth),\n this.resolver.resolveSignIn(assertion as exp.MultiFactorAssertion)\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Compat } from '@firebase/util';\nimport { _savePersistenceForRedirect } from './persistence';\nimport { CompatPopupRedirectResolver } from './popup_redirect';\nimport {\n convertConfirmationResult,\n convertCredential\n} from './user_credential';\n\nexport class User implements compat.User, Compat<exp.User> {\n // Maintain a map so that there's always a 1:1 mapping between new User and\n // legacy compat users\n private static readonly USER_MAP = new WeakMap<exp.User, User>();\n\n readonly multiFactor: compat.MultiFactorUser;\n\n private constructor(readonly _delegate: exp.User) {\n this.multiFactor = exp.multiFactor(_delegate);\n }\n\n static getOrCreate(user: exp.User): User {\n if (!User.USER_MAP.has(user)) {\n User.USER_MAP.set(user, new User(user));\n }\n\n return User.USER_MAP.get(user)!;\n }\n\n delete(): Promise<void> {\n return this._delegate.delete();\n }\n reload(): Promise<void> {\n return this._delegate.reload();\n }\n toJSON(): object {\n return this._delegate.toJSON();\n }\n getIdTokenResult(forceRefresh?: boolean): Promise<compat.IdTokenResult> {\n return this._delegate.getIdTokenResult(forceRefresh);\n }\n getIdToken(forceRefresh?: boolean): Promise<string> {\n return this._delegate.getIdToken(forceRefresh);\n }\n linkAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.linkWithCredential(credential);\n }\n async linkWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.linkWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n async linkWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this.auth,\n exp.linkWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier)\n );\n }\n async linkWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.linkWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async linkWithRedirect(provider: compat.AuthProvider): Promise<void> {\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\n return exp.linkWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n reauthenticateAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.reauthenticateWithCredential(credential);\n }\n async reauthenticateWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth as unknown as exp.Auth,\n exp.reauthenticateWithCredential(\n this._delegate,\n credential as exp.AuthCredential\n )\n );\n }\n reauthenticateWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this.auth,\n exp.reauthenticateWithPhoneNumber(\n this._delegate,\n phoneNumber,\n applicationVerifier\n )\n );\n }\n reauthenticateWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.reauthenticateWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async reauthenticateWithRedirect(\n provider: compat.AuthProvider\n ): Promise<void> {\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\n return exp.reauthenticateWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n sendEmailVerification(\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.sendEmailVerification(this._delegate, actionCodeSettings);\n }\n async unlink(providerId: string): Promise<compat.User> {\n await exp.unlink(this._delegate, providerId);\n return this;\n }\n updateEmail(newEmail: string): Promise<void> {\n return exp.updateEmail(this._delegate, newEmail);\n }\n updatePassword(newPassword: string): Promise<void> {\n return exp.updatePassword(this._delegate, newPassword);\n }\n updatePhoneNumber(phoneCredential: compat.AuthCredential): Promise<void> {\n return exp.updatePhoneNumber(\n this._delegate,\n phoneCredential as exp.PhoneAuthCredential\n );\n }\n updateProfile(profile: {\n displayName?: string | null;\n photoURL?: string | null;\n }): Promise<void> {\n return exp.updateProfile(this._delegate, profile);\n }\n verifyBeforeUpdateEmail(\n newEmail: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.verifyBeforeUpdateEmail(\n this._delegate,\n newEmail,\n actionCodeSettings\n );\n }\n get emailVerified(): boolean {\n return this._delegate.emailVerified;\n }\n get isAnonymous(): boolean {\n return this._delegate.isAnonymous;\n }\n get metadata(): compat.UserMetadata {\n return this._delegate.metadata;\n }\n get phoneNumber(): string | null {\n return this._delegate.phoneNumber;\n }\n get providerData(): Array<compat.UserInfo | null> {\n return this._delegate.providerData;\n }\n get refreshToken(): string {\n return this._delegate.refreshToken;\n }\n get tenantId(): string | null {\n return this._delegate.tenantId;\n }\n get displayName(): string | null {\n return this._delegate.displayName;\n }\n get email(): string | null {\n return this._delegate.email;\n }\n get photoURL(): string | null {\n return this._delegate.photoURL;\n }\n get providerId(): string {\n return this._delegate.providerId;\n }\n get uid(): string {\n return this._delegate.uid;\n }\n private get auth(): exp.Auth {\n return (this._delegate as exp.UserImpl).auth as unknown as exp.Auth;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Provider } from '@firebase/component';\nimport { ErrorFn, Observer, Unsubscribe } from '@firebase/util';\n\nimport {\n _validatePersistenceArgument,\n Persistence,\n _getPersistencesFromRedirect,\n _savePersistenceForRedirect\n} from './persistence';\nimport { _isPopupRedirectSupported } from './platform';\nimport { CompatPopupRedirectResolver } from './popup_redirect';\nimport { User } from './user';\nimport {\n convertConfirmationResult,\n convertCredential\n} from './user_credential';\nimport { ReverseWrapper, Wrapper } from './wrap';\n\nconst _assert: typeof exp._assert = exp._assert;\n\nexport class Auth\n implements compat.FirebaseAuth, Wrapper<exp.Auth>, _FirebaseService\n{\n static Persistence = Persistence;\n readonly _delegate: exp.AuthImpl;\n\n constructor(readonly app: FirebaseApp, provider: Provider<'auth'>) {\n if (provider.isInitialized()) {\n this._delegate = provider.getImmediate() as exp.AuthImpl;\n this.linkUnderlyingAuth();\n return;\n }\n\n const { apiKey } = app.options;\n // TODO: platform needs to be determined using heuristics\n _assert(apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n\n // TODO: platform needs to be determined using heuristics\n _assert(apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n\n // Only use a popup/redirect resolver in browser environments\n const resolver =\n typeof window !== 'undefined' ? CompatPopupRedirectResolver : undefined;\n this._delegate = provider.initialize({\n options: {\n persistence: buildPersistenceHierarchy(apiKey, app.name),\n popupRedirectResolver: resolver\n }\n }) as exp.AuthImpl;\n\n this._delegate._updateErrorMap(exp.debugErrorMap);\n this.linkUnderlyingAuth();\n }\n\n get emulatorConfig(): compat.EmulatorConfig | null {\n return this._delegate.emulatorConfig;\n }\n\n get currentUser(): compat.User | null {\n if (!this._delegate.currentUser) {\n return null;\n }\n\n return User.getOrCreate(this._delegate.currentUser);\n }\n get languageCode(): string | null {\n return this._delegate.languageCode;\n }\n set languageCode(languageCode: string | null) {\n this._delegate.languageCode = languageCode;\n }\n get settings(): compat.AuthSettings {\n return this._delegate.settings;\n }\n get tenantId(): string | null {\n return this._delegate.tenantId;\n }\n set tenantId(tid: string | null) {\n this._delegate.tenantId = tid;\n }\n useDeviceLanguage(): void {\n this._delegate.useDeviceLanguage();\n }\n signOut(): Promise<void> {\n return this._delegate.signOut();\n }\n useEmulator(url: string, options?: { disableWarnings: boolean }): void {\n exp.connectAuthEmulator(this._delegate, url, options);\n }\n applyActionCode(code: string): Promise<void> {\n return exp.applyActionCode(this._delegate, code);\n }\n\n checkActionCode(code: string): Promise<compat.ActionCodeInfo> {\n return exp.checkActionCode(this._delegate, code);\n }\n\n confirmPasswordReset(code: string, newPassword: string): Promise<void> {\n return exp.confirmPasswordReset(this._delegate, code, newPassword);\n }\n\n async createUserWithEmailAndPassword(\n email: string,\n password: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.createUserWithEmailAndPassword(this._delegate, email, password)\n );\n }\n fetchProvidersForEmail(email: string): Promise<string[]> {\n return this.fetchSignInMethodsForEmail(email);\n }\n fetchSignInMethodsForEmail(email: string): Promise<string[]> {\n return exp.fetchSignInMethodsForEmail(this._delegate, email);\n }\n isSignInWithEmailLink(emailLink: string): boolean {\n return exp.isSignInWithEmailLink(this._delegate, emailLink);\n }\n async getRedirectResult(): Promise<compat.UserCredential> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const credential = await exp.getRedirectResult(\n this._delegate,\n CompatPopupRedirectResolver\n );\n if (!credential) {\n return {\n credential: null,\n user: null\n };\n }\n return convertCredential(this._delegate, Promise.resolve(credential));\n }\n\n // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\n // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it\n // out of autogenerated documentation pages to reduce accidental misuse.\n addFrameworkForLogging(framework: string): void {\n exp.addFrameworkForLogging(this._delegate, framework);\n }\n\n onAuthStateChanged(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n errorFn?: (error: compat.Error) => unknown,\n completed?: Unsubscribe\n ): Unsubscribe {\n const { next, error, complete } = wrapObservers(\n nextOrObserver,\n errorFn,\n completed\n );\n return this._delegate.onAuthStateChanged(next!, error, complete);\n }\n onIdTokenChanged(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n errorFn?: (error: compat.Error) => unknown,\n completed?: Unsubscribe\n ): Unsubscribe {\n const { next, error, complete } = wrapObservers(\n nextOrObserver,\n errorFn,\n completed\n );\n return this._delegate.onIdTokenChanged(next!, error, complete);\n }\n sendSignInLinkToEmail(\n email: string,\n actionCodeSettings: compat.ActionCodeSettings\n ): Promise<void> {\n return exp.sendSignInLinkToEmail(this._delegate, email, actionCodeSettings);\n }\n sendPasswordResetEmail(\n email: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.sendPasswordResetEmail(\n this._delegate,\n email,\n actionCodeSettings || undefined\n );\n }\n async setPersistence(persistence: string): Promise<void> {\n _validatePersistenceArgument(this._delegate, persistence);\n let converted;\n switch (persistence) {\n case Persistence.SESSION:\n converted = exp.browserSessionPersistence;\n break;\n case Persistence.LOCAL:\n // Not using isIndexedDBAvailable() since it only checks if indexedDB is defined.\n const isIndexedDBFullySupported = await exp\n ._getInstance<exp.PersistenceInternal>(exp.indexedDBLocalPersistence)\n ._isAvailable();\n converted = isIndexedDBFullySupported\n ? exp.indexedDBLocalPersistence\n : exp.browserLocalPersistence;\n break;\n case Persistence.NONE:\n converted = exp.inMemoryPersistence;\n break;\n default:\n return exp._fail(exp.AuthErrorCode.ARGUMENT_ERROR, {\n appName: this._delegate.name\n });\n }\n\n return this._delegate.setPersistence(converted);\n }\n\n signInAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.signInWithCredential(credential);\n }\n signInAnonymously(): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInAnonymously(this._delegate)\n );\n }\n signInWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n signInWithCustomToken(token: string): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithCustomToken(this._delegate, token)\n );\n }\n signInWithEmailAndPassword(\n email: string,\n password: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithEmailAndPassword(this._delegate, email, password)\n );\n }\n signInWithEmailLink(\n email: string,\n emailLink?: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithEmailLink(this._delegate, email, emailLink)\n );\n }\n signInWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this._delegate,\n exp.signInWithPhoneNumber(\n this._delegate,\n phoneNumber,\n applicationVerifier\n )\n );\n }\n async signInWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n return convertCredential(\n this._delegate,\n exp.signInWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async signInWithRedirect(provider: compat.AuthProvider): Promise<void> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n\n await _savePersistenceForRedirect(this._delegate);\n return exp.signInWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n updateCurrentUser(user: compat.User | null): Promise<void> {\n // remove ts-ignore once overloads are defined for exp functions to accept compat objects\n // @ts-ignore\n return this._delegate.updateCurrentUser(user);\n }\n verifyPasswordResetCode(code: string): Promise<string> {\n return exp.verifyPasswordResetCode(this._delegate, code);\n }\n unwrap(): exp.Auth {\n return this._delegate;\n }\n _delete(): Promise<void> {\n return this._delegate._delete();\n }\n private linkUnderlyingAuth(): void {\n (this._delegate as unknown as ReverseWrapper<Auth>).wrapped = () => this;\n }\n}\n\nfunction wrapObservers(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n error?: (error: compat.Error) => unknown,\n complete?: Unsubscribe\n): Partial<Observer<exp.User | null>> {\n let next = nextOrObserver;\n if (typeof nextOrObserver !== 'function') {\n ({ next, error, complete } = nextOrObserver);\n }\n\n // We know 'next' is now a function\n const oldNext = next as (a: compat.User | null) => unknown;\n\n const newNext = (user: exp.User | null): unknown =>\n oldNext(user && User.getOrCreate(user as exp.User));\n return {\n next: newNext,\n error: error as ErrorFn,\n complete\n };\n}\n\nfunction buildPersistenceHierarchy(\n apiKey: string,\n appName: string\n): exp.Persistence[] {\n // Note this is slightly different behavior: in this case, the stored\n // persistence is checked *first* rather than last. This is because we want\n // to prefer stored persistence type in the hierarchy. This is an empty\n // array if window is not available or there is no pending redirect\n const persistences = _getPersistencesFromRedirect(apiKey, appName);\n\n // If \"self\" is available, add indexedDB\n if (\n typeof self !== 'undefined' &&\n !persistences.includes(exp.indexedDBLocalPersistence)\n ) {\n persistences.push(exp.indexedDBLocalPersistence);\n }\n\n // If \"window\" is available, add HTML Storage persistences\n if (typeof window !== 'undefined') {\n for (const persistence of [\n exp.browserLocalPersistence,\n exp.browserSessionPersistence\n ]) {\n if (!persistences.includes(persistence)) {\n persistences.push(persistence);\n }\n }\n }\n\n // Add in-memory as a final fallback\n if (!persistences.includes(exp.inMemoryPersistence)) {\n persistences.push(exp.inMemoryPersistence);\n }\n\n return persistences;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _castAuth } from '../src/core/auth/auth_impl';\nimport { Auth } from '../src/model/public_types';\n\n/**\n * This interface is intended only for use by @firebase/auth-compat, do not use directly\n */\nexport * from '../index';\n\nexport { SignInWithIdpResponse } from '../src/api/authentication/idp';\nexport { AuthErrorCode } from '../src/core/errors';\nexport { PersistenceInternal } from '../src/core/persistence';\nexport { _persistenceKeyName } from '../src/core/persistence/persistence_user_manager';\nexport { UserImpl } from '../src/core/user/user_impl';\nexport { _getInstance } from '../src/core/util/instantiator';\nexport {\n PopupRedirectResolverInternal,\n EventManager,\n AuthEventType\n} from '../src/model/popup_redirect';\nexport { UserCredentialInternal, UserParameters } from '../src/model/user';\nexport { AuthInternal, ConfigInternal } from '../src/model/auth';\nexport { DefaultConfig, AuthImpl, _castAuth } from '../src/core/auth/auth_impl';\n\nexport { ClientPlatform, _getClientVersion } from '../src/core/util/version';\n\nexport { _generateEventId } from '../src/core/util/event_id';\nexport { TaggedWithTokenResponse } from '../src/model/id_token';\nexport { _fail, _assert } from '../src/core/util/assert';\nexport { AuthPopup } from '../src/platform_browser/util/popup';\nexport { _getRedirectResult } from '../src/platform_browser/strategies/redirect';\nexport { _overrideRedirectResult } from '../src/core/strategies/redirect';\nexport { cordovaPopupRedirectResolver } from '../src/platform_cordova/popup_redirect/popup_redirect';\nexport { FetchProvider } from '../src/core/util/fetch_provider';\nexport { SAMLAuthCredential } from '../src/core/credentials/saml';\n\n// This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\n// It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out\n// of autogenerated documentation pages to reduce accidental misuse.\nexport function addFrameworkForLogging(auth: Auth, framework: string): void {\n _castAuth(auth)._logFramework(framework);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { UserInternal } from '../../model/user';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport async function signInAnonymously(auth: Auth): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser as UserInternal,\n providerId: null,\n operationType: OperationType.SIGN_IN\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response,\n true\n );\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport firebase from '@firebase/app-compat';\nimport { Compat } from '@firebase/util';\nimport { unwrap } from './wrap';\n\nexport class PhoneAuthProvider\n implements compat.PhoneAuthProvider, Compat<exp.PhoneAuthProvider>\n{\n providerId = 'phone';\n readonly _delegate: exp.PhoneAuthProvider;\n\n static PHONE_SIGN_IN_METHOD = exp.PhoneAuthProvider.PHONE_SIGN_IN_METHOD;\n static PROVIDER_ID = exp.PhoneAuthProvider.PROVIDER_ID;\n\n static credential(\n verificationId: string,\n verificationCode: string\n ): compat.AuthCredential {\n return exp.PhoneAuthProvider.credential(verificationId, verificationCode);\n }\n\n constructor() {\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\n // @ts-ignore\n this._delegate = new exp.PhoneAuthProvider(unwrap(firebase.auth!()));\n }\n\n verifyPhoneNumber(\n phoneInfoOptions:\n | string\n | compat.PhoneSingleFactorInfoOptions\n | compat.PhoneMultiFactorEnrollInfoOptions\n | compat.PhoneMultiFactorSignInInfoOptions,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<string> {\n return this._delegate.verifyPhoneNumber(\n // The implementation matches but the types are subtly incompatible\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n phoneInfoOptions as any,\n applicationVerifier\n );\n }\n\n unwrap(): exp.PhoneAuthProvider {\n return this._delegate;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { FirebaseApp } from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Compat } from '@firebase/util';\n\nconst _assert: typeof exp._assert = exp._assert;\n\nexport class RecaptchaVerifier\n implements compat.RecaptchaVerifier, Compat<exp.ApplicationVerifier>\n{\n readonly _delegate: exp.RecaptchaVerifier;\n type: string;\n constructor(\n container: HTMLElement | string,\n parameters?: object | null,\n app: FirebaseApp = firebase.app()\n ) {\n // API key is required for web client RPC calls.\n _assert(app.options?.apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n this._delegate = new exp.RecaptchaVerifier(\n container,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parameters as any,\n\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\n // @ts-ignore\n app.auth!()\n );\n this.type = this._delegate.type;\n }\n clear(): void {\n this._delegate.clear();\n }\n render(): Promise<number> {\n return this._delegate.render();\n }\n verify(): Promise<string> {\n return this._delegate.verify();\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { jsonEval, stringify } from '@firebase/util';\n\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key: string, value: unknown | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key: string): unknown {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nexport class MemoryStorage {\n private cache_: { [k: string]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: Window;\n\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport const priorityHashText = function (priority: string | number): string {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n } else {\n return 'string:' + priority;\n }\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n */\nexport const validatePriorityNode = function (priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val as Indexable, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\n\nlet nodeFromJSON: (a: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport class PriorityIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n makePost(indexValue: unknown, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nexport class SyncPoint {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n readonly views: Map<string, View> = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\n}\n\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree<SyncPoint> = new ImmutableTree<SyncPoint>(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map<number, string> = new Map();\n readonly queryToTagMap: Map<string, number> = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), path, changeTree)\n );\n}\n\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree<boolean>(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\n): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (\n maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault =\n -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag: number | null = null;\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\n}\n\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\n): Event[] {\n const path = query._path;\n\n let serverCache: Node | null = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->\n * <incremented total> as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\n}\n\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree<SyncPoint>,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree<SyncPoint>,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n } else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree<SyncPoint>\n): View[] {\n return subtree.fold<View[]>((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n assert(\n !syncPointHasCompleteView(subtree.value),\n \"If we're adding a query, it shouldn't be shadowed\"\n );\n } else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold<QueryContext[]>(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n }\n );\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { repoManagerDatabaseFromApp } from './api/Database';\n\nexport function registerDatabase(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'database',\n (container, { instanceIdentifier: url }) => {\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\n\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nexport const LUIDGenerator: () => number = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nexport const sha1 = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\nconst buildLogMessage_ = function (...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nexport const enableLogging = function (\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || logger_ === true || logger_ === false,\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\nexport const log = function (...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\nexport const fatal = function (...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\nexport const warn = function (...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexport const warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\nexport const warnAboutUnsupportedMethod = function (methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nexport const isInvalidJSONNumber = function (data: unknown): boolean {\n return (\n typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY)\n );\n};\n\nexport const executeWhenDOMReady = function (fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).attachEvent('onload', wrappedFn);\n\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nexport const nameCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @returns {!number} comparison result.\n */\nexport const stringCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\nexport const requireKey = function (\n key: string,\n obj: { [k: string]: unknown }\n): unknown {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\nexport const ObjectToUniqueKey = function (obj: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\n\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nexport const splitStringBySize = function (\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\n return context ? callback.bind(context) : callback;\n};\n\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nexport const doubleToIEEE754String = function (v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n } else {\n s = v < 0;\n v = Math.abs(v);\n\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nexport const isChromeExtensionContentScript = function (): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nexport const isWindowsStoreApp = function (): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a Javascript Error\n */\nexport function errorForServerCode(code: string, query: QueryContext): Error {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n } else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query._path.toString() + ': ' + reason\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code.toUpperCase();\n return error;\n}\n\n/**\n * Used to test for integer-looking strings\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in kyes, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nexport const exceptionGuard = function (fn: () => void) {\n try {\n fn();\n } catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function (): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\n\n/**\n * Export a property of an object using a getter function.\n */\nexport const exportPropGetter = function (\n object: object,\n name: string,\n fnGet: () => unknown\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n\n return timeout;\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n constructor(\n private appName_: string,\n private appCheckProvider?: Provider<AppCheckInternalComponentName>\n ) {\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult> {\n if (!this.appCheck) {\n return new Promise<AppCheckTokenResult>((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timoeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName_}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData>;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider<FirebaseAuthInternalName>\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData> {\n if (!this.auth_) {\n return new Promise<FirebaseAuthTokenData>((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timoeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData> {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false\n ) {\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this._host;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n\n const pairs: string[] = [];\n\n each(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter<T>(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { exceptionGuard } from '../../core/util/util';\n\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nexport class PacketReceiver {\n pendingResponses: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum: number, data: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1 as string;\n this.password = arg2 as string;\n } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1 as number, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN as number, data as unknown[]);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (\n !BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\n }\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data: {}) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\n }\n\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n */\n private incrementIncomingBytes_(args: unknown) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n outstandingRequests = new Set<number>();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\n\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n currentSerial = Math.floor(Math.random() * 100000000);\n\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => void;\n\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(\n commandCB: (command: string, ...args: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '<script>document.domain=\"' + currentDomain + '\";</script>';\n }\n const iframeContents = '<html><body>' + script + '</body></html>';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) {}\n }\n\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n private newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n (nextSeg.d as unknown[]).length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum: number, totalsegs: number, data: unknown) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\n\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { Transport } from './Transport';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed(): boolean {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess) as object;\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n private extractFrameCount_(data: string): string | null {\n assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess: { [k: string]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data: {}) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n private sendString_(str: string) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\n\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n }\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\n private onMessage_: (a: {}) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\n this.lastSessionId\n );\n\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) as any;\n }\n }\n\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: Indexable) => {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: unknown }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\n } else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n\n private onControl_(controlData: { [k: string]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(\n payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n }\n );\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n * @param handshake - The handshake data returned from the server\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }): void {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n this.sessionId\n );\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === RealtimeState.CONNECTING) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\n\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nexport abstract class ServerActions {\n abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise<string>;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n constructor(private allowedEvents_: string[]) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @returns {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\n\nexport class Path {\n pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n\n return pathString || '/';\n }\n}\n\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n\n return new Path(pieces, 0);\n}\n\n/**\n * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\n }\n}\n\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n\n/**\n * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nexport class ValidationPath {\n parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\n\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: unknown;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => void;\n}\n\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n private interruptReasons_: { [reason: string]: boolean } = {};\n private readonly listens: Map<\n /* path */ string,\n Map</* queryId */ string, ListenSpec>\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: object) => void) | null = null;\n lastSessionId: string | null = null;\n\n private establishConnectionTimer_: number | null = null;\n\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\n private authToken_: string | null = null;\n private appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider,\n private authOverride_?: object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n get(query: QueryContext): Promise<string> {\n this.initConnection_();\n\n const deferred = new Deferred<string>();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\n\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens.get(pathString)!.has(queryId),\n `listen() called twice for same path/queryId.`\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n private sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n\n const action = 'q';\n\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n private static warnOnListenWarnings_(payload: unknown, query: QueryContext) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n\n refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\n }\n }\n\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: unknown } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n }\n );\n }\n }\n\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, tag: number | null) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n }\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.initConnection_();\n\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: unknown }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete) {\n onComplete(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n reportStats(stats: { [k: string]: unknown }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'apc') {\n this.onAppCheckRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n } else {\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n }\n\n private onReady_(timestamp: number, sessionId: string) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\n\n private initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt =\n new Date().getTime() - this.lastConnectionAttemptTime_;\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg: object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onSecurityDebugPacket_(body: { [k: string]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n\n /**\n * Sends client stats for first connection\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\n }\n\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param childName - The name of the child to retrieve.\n * @returns The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param path - The path of the child to retrieve.\n * @returns The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param path - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): unknown;\n\n /**\n * @param exportFormat - True for export format (also wire protocol format).\n * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare(): Comparator<NamedNode> {\n return this.compare.bind(this);\n }\n\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @returns a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node: Node): boolean {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379\\@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator<K, V, T> {\n private nodeStack_: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode<K, V>;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n } else {\n result = { key: node.key, value: node.value } as unknown as T;\n }\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as unknown as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode<K, V> {\n color: boolean;\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>);\n }\n\n static RED = true;\n static BLACK = false;\n\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return (\n this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @returns The minimum node in the tree.\n */\n private min_(): LLRBNode<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).min_();\n }\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @returns New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin_(), null);\n return n.fixUp_();\n }\n\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(\n key: K,\n comparator: Comparator<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode<K, V> {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode<K, V>).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode<K, V> {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode<K, V> {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode<K, V>;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode<K, V> {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode<K, V>;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode<K, V> {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n check_(): number {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode<K, V> {\n key: K;\n value: V;\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\n return this;\n }\n\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n return new LLRBNode(key, value, null);\n }\n\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap<K, V> {\n /**\n * Always use the same empty node, to reduce memory.\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(\n private comparator_: Comparator<K>,\n private root_:\n | LLRBNode<K, V>\n | LLRBEmptyNode<K, V> = SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>\n ) {}\n\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key: K, value: V): SortedMap<K, V> {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key: K): SortedMap<K, V> {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\n\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return this.root_.inorderTraversal(action);\n }\n\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\n\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator<T>(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom<T>(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom<T>(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator<T>(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(\n private readonly value_: string | number | boolean | Indexable,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: string, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(\n childName,\n newChildNode\n ).updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n pathPopFront(path),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): boolean {\n return false;\n }\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n }\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\n }\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n } else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n constructor(length: number) {\n const logBase2 = (num: number) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nexport const buildChildSet = function <K, V>(\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap<K, V> {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode<K, V> | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length === 0) {\n return null;\n } else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function (base12: Base12Num): LLRBNode<K, V> {\n let node: LLRBNode<K, V> = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function (chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n attachPennant(\n new LLRBNode(\n key,\n namedNode.node as unknown as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function (pennant: LLRBNode<K, V>) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap<K, V>(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap<NamedNode, Node> | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap<NamedNode, Node> | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap<string, Node>\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap<string, Node>\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap<NamedNode, Node>, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap<string, Node>\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap<NamedNode, Node>) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n } else {\n // No record of this child\n return indexedChildren;\n }\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap<string, Node>,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap<string, Node>(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(\n private readonly children_: SortedMap<string, Node>,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key: string, childNode: Node) => {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key as unknown as number] = obj[key];\n }\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n }\n\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\n }\n\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n forEachChild(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator<string | NamedNode, Node, NamedNode> {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator<string | NamedNode, Node, NamedNode> {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator<string | NamedNode, Node, NamedNode> {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator<string | NamedNode, Node, NamedNode> {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap<NamedNode, Node> | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap<string, Node>(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\n\nconst USE_HINZE = true;\n\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nexport function nodeFromJSON(\n json: unknown | null,\n priority: unknown = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | Indexable;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap<string, Node>;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n each(json, (key: string, childData: unknown) => {\n if (contains(json as object, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : (oldEventCache.getLastChild(this.index_) as NamedNode);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))\n ) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildAdded(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n\n private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\n LIMIT = 'l',\n VIEW_FROM = 'vf',\n VIEW_FROM_LEFT = 'l',\n VIEW_FROM_RIGHT = 'r',\n INDEX = 'i'\n}\n\n/**\n * REST Query Constants\n */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\n\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft(): boolean {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue(): unknown {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue(): unknown {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\n\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record<string, string | number> {\n const qs: Record<string, string | number> = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record<string, unknown> {\n const obj: Record<string, unknown> = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\n\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => void = logWrapper('p:rest:');\n\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n private listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query._path.toString();\n }\n }\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error === 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise<string> {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred<string>();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\n\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map<string, SparseSnapshotTree>;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, path);\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\n\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.children.size === 0;\n } else {\n return true;\n }\n }\n}\n\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\n\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\n\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n each(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree<boolean>,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\n\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /** @inheritDoc */ public source: OperationSource,\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public children: ImmutableTree<Node>\n ) {}\n operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n } else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\n\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nexport class CacheNode {\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\n\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\n\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n}\n\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\n\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap<string, ImmutableTree<null>>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap<string, ImmutableTree<null>> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap<string, ImmutableTree<null>>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree<T> {\n static fromObject<T>(obj: { [k: string]: T }): ImmutableTree<T> {\n let tree: ImmutableTree<T> = new ImmutableTree<T>(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree<T>\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\n\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree<T>(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree<T>(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree<T>(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree<T>(null);\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\n }\n }\n\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n } else {\n return null;\n }\n }\n }\n\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree<T>): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree<T>(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold<V>(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\n */\n private fold_<V>(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(\n (childKey: string, childTree: ImmutableTree<T>) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n }\n );\n return fn(pathSoFar, this.value, accum);\n }\n\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath<V>(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_<V>(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree<T> {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree<T> {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree<T>(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree<T>) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\nimport { each } from './util/util';\n\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nexport class CompoundWrite {\n constructor(public writeTree_: ImmutableTree<Node>) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n\n/**\n * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree<Node>(null)\n );\n return new CompoundWrite(newWriteTree);\n }\n}\n\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n } else {\n return null;\n }\n}\n\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n (node as ChildrenNode).forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.writeTree_.isEmpty();\n}\n\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree<Node>,\n node: Node\n): Node {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n } else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = applySubtreeWrite(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap wil be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): boolean {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n\n if (!removedWriteWasVisible) {\n return false;\n } else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n } else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write: WriteRecord) {\n return write.visible;\n}\n\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n): CompoundWrite {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n\n/**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())\n ) {\n return null;\n } else {\n const filter = function (write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\n } else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n } else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\n}\n\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n } else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\n }\n }\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\n }\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n let toIterate: Node;\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n } else {\n return [];\n }\n}\n\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n */\nexport interface WriteTree {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n */\n visibleWrites: CompoundWrite;\n\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n */\n allWrites: WriteRecord[];\n\n lastWriteId: number;\n}\n\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n}\n\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerChildren\n ) as ChildrenNode;\n}\n\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n path,\n existingEventSnap,\n existingServerSnap\n );\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerData,\n startPost,\n count,\n reverse,\n index\n );\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n */\nexport interface WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n */\n readonly treePath: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n */\n readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map<string, Change> = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = change.childName!;\n assert(\n type === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n getCompleteChild(childKey: string): Node | null;\n\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n null\n );\n } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()\n ) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree<Node>,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree<Node>\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree<Node>,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (\n viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()\n ) {\n return viewCache;\n }\n\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree: ImmutableTree<Node>;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree<Node>(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree<boolean>,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree<Node>(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = new ImmutableTree<Node>(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\n\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (\n view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n } else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\n */\nexport const generateWithValues = function (\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\n};\n\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode<T> {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record<string, TreeNode<T>>;\n childCount: number;\n value?: T;\n}\n\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nexport class Tree<T> {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree<T> | null = null,\n public node: TreeNode<T> = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree<T>(tree: Tree<T>, pathObj: string | Path): Tree<T> {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree<T>(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue<T>(tree: Tree<T>): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue<T>(tree: Tree<T>, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren<T>(tree: Tree<T>): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whethe rthe tree is empty (no value or children).\n */\nexport function treeIsEmpty<T>(tree: Tree<T>): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode<T>) => {\n action(new Tree<T>(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n\n/**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath<T>(tree: Tree<T>) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents<T>(tree: Tree<T>) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild<T>(tree: Tree<T>, childName: string, child: Tree<T>) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\nexport const isValidKey = function (key: unknown): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\nexport const isValidPathString = function (pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\nexport const isValidRootPathString = function (pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\nexport const isValidPriority = function (priority: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.sv'))\n );\n};\n\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\n */\nexport const validateFirebaseData = function (\n errorPrefix: string,\n data: unknown,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\n }\n\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n }\n\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\n};\n\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n each(data, (key: string, value: unknown) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).'\n );\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function (\n fnName: string,\n priority: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).'\n );\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").'\n );\n }\n};\n\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\n\n if (!isValidPathString(pathString)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n }\n};\n\nexport const validateRootPathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === 'object' && !(typeof val === 'object') && val)\n ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\nimport { Event } from './Event';\n\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, path)\n );\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst enum TransactionStatus {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n RUN,\n\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n SENT,\n\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n COMPLETED,\n\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n}\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree<Transaction[]>();\n\n // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n}\n\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n}\n\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise<Node> {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName: string, childNode: unknown) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n}\n\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code;\n callback(error);\n }\n });\n }\n}\n\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree<Transaction[]> = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /** @type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n } else {\n queue[i].status = TransactionStatus.RUN;\n }\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n repoRerunTransactions(repo, path);\n }\n },\n latestHash\n );\n}\n\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\n path: Path\n): Tree<Transaction[]> {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree<Transaction[]>\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree<Transaction[]>,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree<Transaction[]>\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree<Transaction[]>) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree<Transaction[]>) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree<Transaction[]>\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\n\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\n\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use <YOUR FIREBASE>.firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly,\n nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\n );\n\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n } else {\n colonInd = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\n\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexport const nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars: number[] = [];\n\n return function (now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n } else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexigographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\n */\nexport type EventType =\n | 'value'\n | 'child_added'\n | 'child_changed'\n | 'child_moved'\n | 'child_removed';\n\n/**\n * Encapsulates the data needed to raise an event\n */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(\n public eventType: EventType,\n public eventRegistration: EventRegistration,\n public snapshot: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise<void> {\n const deferred = new Deferred<void>();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise<void> {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred<void>();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise<void> {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred<void>();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise<void> {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred<void>();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise<void> {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred<void>();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record<string, unknown>,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n 'Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).'\n );\n }\n } else {\n assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val() as string | number | null;\n }\n\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `DataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: DataSnapshot) => boolean | void): boolean {\n if (this._node.isLeafNode()) {\n return false;\n }\n\n const childrenNode = this._node as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(\n new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick<Promise<ReferenceImpl>, 'then' | 'catch'> {}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thennablePushRef: Partial<ThenableReferenceImpl> = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise<ReferenceImpl>;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n return thennablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise<void> {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise<void> {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred<void>();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise<void> {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred<void>();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise<void> {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred<void>();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise<void> {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred<void>();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record<string, unknown>,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise<DataSnapshot> {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\n\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply<T>(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type: 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type: 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type: 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type: 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type: 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type: 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type: 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type: 'orderByKey';\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type: 'orderByPriority';\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type: 'orderByValue';\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type: 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n host: string,\n port: number,\n tokenProvider?: AuthTokenProvider\n): void {\n repo.repoInfo_ = new RepoInfo(\n `${host}:${port}`,\n /* secure= */ false,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n appCheckProvider?: Provider<AppCheckInternalComponentName>,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app.name, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n}\n\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise<void> {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated\n * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with\n * with default settings if no instance exists or if the existing instance uses\n * a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n * <p>Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n if (db._instanceStarted) {\n fatal(\n 'Cannot call useEmulator() after instance has already been initialized.'\n );\n }\n\n const repo = db._repoInternal;\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise<TransactionResult> {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred<TransactionResult>();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function (\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function (\n data: unknown,\n onEcho: (a: unknown) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @internal\n */\nexport const hijackHash = function (newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (\n pathString,\n data,\n onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nconst logClient = new Logger('@firebase/database-compat');\n\nexport const warn = function (msg: string) {\n const message = 'FIREBASE WARNING: ' + msg;\n logClient.warn(message);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnDisconnect as ModularOnDisconnect } from '@firebase/database';\nimport { validateArgCount, validateCallback, Compat } from '@firebase/util';\n\nimport { warn } from '../util/util';\nexport class OnDisconnect implements Compat<ModularOnDisconnect> {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n const result = this._delegate.cancel();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n const result = this._delegate.remove();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n set(value: unknown, onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n const result = this._delegate.set(value);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n value: unknown,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'OnDisconnect.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n const result = this._delegate.setWithPriority(value, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n objectToMerge: Record<string, unknown>,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n 'Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.'\n );\n }\n validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n const result = this._delegate.update(objectToMerge);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateArgCount } from '@firebase/util';\n\nimport { DataSnapshot } from './Reference';\n\nexport class TransactionResult {\n /**\n * A type for the resolve value of Firebase.transaction.\n */\n constructor(public committed: boolean, public snapshot: DataSnapshot) {}\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): object {\n validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OnDisconnect as ModularOnDisconnect,\n off,\n onChildAdded,\n onChildChanged,\n onChildMoved,\n onChildRemoved,\n onValue,\n EventType,\n limitToFirst,\n query,\n limitToLast,\n orderByChild,\n orderByKey,\n orderByValue,\n orderByPriority,\n startAt,\n startAfter,\n endAt,\n endBefore,\n equalTo,\n get,\n set,\n update,\n setWithPriority,\n remove,\n setPriority,\n push,\n runTransaction,\n child,\n DataSnapshot as ModularDataSnapshot,\n Query as ExpQuery,\n DatabaseReference as ModularReference,\n _QueryImpl,\n _ReferenceImpl,\n _validatePathString,\n _validateWritablePath,\n _UserCallback,\n _QueryParams\n} from '@firebase/database';\nimport {\n Compat,\n Deferred,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '@firebase/util';\n\nimport { warn } from '../util/util';\nimport { validateBoolean, validateEventType } from '../util/validation';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\n\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nexport class DataSnapshot implements Compat<ModularDataSnapshot> {\n constructor(\n readonly _database: Database,\n readonly _delegate: ModularDataSnapshot\n ) {}\n\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n val(): unknown {\n validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this._delegate.val();\n }\n\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n exportVal(): unknown {\n validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this._delegate.exportVal();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): unknown {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @returns Whether the snapshot contains a non-null value, or is empty.\n */\n exists(): boolean {\n validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return this._delegate.exists();\n }\n\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param path - Path to a child.\n * @returns DataSnapshot for child node.\n */\n child(path: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n path = String(path);\n _validatePathString('DataSnapshot.child', 'path', path, false);\n return new DataSnapshot(this._database, this._delegate.child(path));\n }\n\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param path - Path to a child.\n * @returns Whether the child exists.\n */\n hasChild(path: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n return this._delegate.hasChild(path);\n }\n\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @returns The priority.\n */\n getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n return this._delegate.priority;\n }\n\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param action - Callback function to be called\n * for each child.\n * @returns True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n forEach(action: (snapshot: DataSnapshot) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 'action', action, false);\n return this._delegate.forEach(expDataSnapshot =>\n action(new DataSnapshot(this._database, expDataSnapshot))\n );\n }\n\n /**\n * Returns whether this DataSnapshot has children.\n * @returns True if the DataSnapshot contains 1 or more child nodes.\n */\n hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n return this._delegate.hasChildren();\n }\n\n get key() {\n return this._delegate.key;\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @returns The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this._delegate.size;\n }\n\n /**\n * @returns The Firebase reference for the location this snapshot's data came\n * from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return new Reference(this._database, this._delegate.ref);\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\nexport interface SnapshotCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n}\n\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nexport class Query implements Compat<ExpQuery> {\n constructor(readonly database: Database, readonly _delegate: ExpQuery) {}\n\n on(\n eventType: string,\n callback: SnapshotCallback,\n cancelCallbackOrContext?: ((a: Error) => unknown) | object | null,\n context?: object | null\n ): SnapshotCallback {\n validateArgCount('Query.on', 2, 4, arguments.length);\n validateCallback('Query.on', 'callback', callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n const valueCallback = (expSnapshot, previousChildName?) => {\n callback.call(\n ret.context,\n new DataSnapshot(this.database, expSnapshot),\n previousChildName\n );\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = ret.cancel?.bind(ret.context);\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n default:\n throw new Error(\n errorPrefix('Query.on', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n }\n\n off(\n eventType?: string,\n callback?: SnapshotCallback,\n context?: object | null\n ): void {\n validateArgCount('Query.off', 0, 3, arguments.length);\n validateEventType('Query.off', eventType, true);\n validateCallback('Query.off', 'callback', callback, true);\n validateContextObject('Query.off', 'context', context, true);\n if (callback) {\n const valueCallback: _UserCallback = () => {};\n valueCallback.userCallback = callback;\n valueCallback.context = context;\n off(this._delegate, eventType as EventType, valueCallback);\n } else {\n off(this._delegate, eventType as EventType | undefined);\n }\n }\n\n /**\n * Get the server-value for this query, or return a cached value if not connected.\n */\n get(): Promise<DataSnapshot> {\n return get(this._delegate).then(expSnapshot => {\n return new DataSnapshot(this.database, expSnapshot);\n });\n }\n\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n */\n once(\n eventType: string,\n callback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise<DataSnapshot> {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateCallback('Query.once', 'callback', callback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n failureCallbackOrContext,\n context\n );\n const deferred = new Deferred<DataSnapshot>();\n const valueCallback: _UserCallback = (expSnapshot, previousChildName?) => {\n const result = new DataSnapshot(this.database, expSnapshot);\n if (callback) {\n callback.call(ret.context, result, previousChildName);\n }\n deferred.resolve(result);\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = (error: Error) => {\n if (ret.cancel) {\n ret.cancel.call(ret.context, error);\n }\n deferred.reject(error);\n };\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n default:\n throw new Error(\n errorPrefix('Query.once', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToLast(limit)));\n }\n\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n */\n orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, orderByChild(path)));\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByKey()));\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByPriority()));\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByValue()));\n }\n\n startAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAt', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAt(value, name))\n );\n }\n\n startAfter(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAfter', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAfter(value, name))\n );\n }\n\n endAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endAt', 0, 2, arguments.length);\n return new Query(this.database, query(this._delegate, endAt(value, name)));\n }\n\n endBefore(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endBefore', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, endBefore(value, name))\n );\n }\n\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n */\n equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, equalTo(value, name))\n );\n }\n\n /**\n * @returns URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n return this._delegate.toString();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n toJSON() {\n // An optional spacer argument is unnecessary for a string.\n validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n */\n isEqual(other: Query): boolean {\n validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n const error =\n 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n return this._delegate.isEqual(other._delegate);\n }\n\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param fnName - The function name (on or once)\n *\n */\n private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): { cancel: ((a: Error) => void) | undefined; context: object | undefined } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: object | null;\n } = { cancel: undefined, context: undefined };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 'cancel', ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 'context', ret.context, true);\n } else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n } else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext as (a: Error) => void;\n } else {\n throw new Error(\n errorPrefix(fnName, 'cancelOrContext') +\n ' must either be a cancel callback or a context object.'\n );\n }\n }\n return ret;\n }\n\n get ref(): Reference {\n return new Reference(\n this.database,\n new _ReferenceImpl(this._delegate._repo, this._delegate._path)\n );\n }\n}\n\nexport class Reference extends Query implements Compat<ModularReference> {\n then: Promise<Reference>['then'];\n catch: Promise<Reference>['catch'];\n\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n */\n constructor(\n readonly database: Database,\n readonly _delegate: ModularReference\n ) {\n super(\n database,\n new _QueryImpl(\n _delegate._repo,\n _delegate._path,\n new _QueryParams(),\n false\n )\n );\n }\n\n /** @returns {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n return this._delegate.key;\n }\n\n child(pathString: string): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n return new Reference(this.database, child(this._delegate, pathString));\n }\n\n /** @returns {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n const parent = this._delegate.parent;\n return parent ? new Reference(this.database, parent) : null;\n }\n\n /** @returns {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n return new Reference(this.database, this._delegate.root);\n }\n\n set(\n newVal: unknown,\n onComplete?: (error: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateCallback('Reference.set', 'onComplete', onComplete, true);\n const result = set(this._delegate, newVal);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n values: object,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n\n if (Array.isArray(values)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < values.length; ++i) {\n newObjectToMerge['' + i] = values[i];\n }\n values = newObjectToMerge;\n warn(\n 'Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.'\n );\n }\n _validateWritablePath('Reference.update', this._delegate._path);\n validateCallback('Reference.update', 'onComplete', onComplete, true);\n\n const result = update(this._delegate, values);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n newVal: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'Reference.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n\n const result = setWithPriority(this._delegate, newVal, newPriority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateCallback('Reference.remove', 'onComplete', onComplete, true);\n\n const result = remove(this._delegate);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n transaction(\n transactionUpdate: (currentData: unknown) => unknown,\n onComplete?: (\n error: Error | null,\n committed: boolean,\n dataSnapshot: DataSnapshot | null\n ) => void,\n applyLocally?: boolean\n ): Promise<TransactionResult> {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateCallback(\n 'Reference.transaction',\n 'transactionUpdate',\n transactionUpdate,\n false\n );\n validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n validateBoolean(\n 'Reference.transaction',\n 'applyLocally',\n applyLocally,\n true\n );\n\n const result = runTransaction(this._delegate, transactionUpdate, {\n applyLocally\n }).then(\n transactionResult =>\n new TransactionResult(\n transactionResult.committed,\n new DataSnapshot(this.database, transactionResult.snapshot)\n )\n );\n if (onComplete) {\n result.then(\n transactionResult =>\n onComplete(\n null,\n transactionResult.committed,\n transactionResult.snapshot\n ),\n error => onComplete(error, false, null)\n );\n }\n return result;\n }\n\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n\n const result = setPriority(this._delegate, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n push(value?: unknown, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateCallback('Reference.push', 'onComplete', onComplete, true);\n\n const expPromise = push(this._delegate, value);\n const promise = expPromise.then(\n expRef => new Reference(this.database, expRef)\n );\n\n if (onComplete) {\n promise.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n\n const result = new Reference(this.database, expPromise);\n result.then = promise.then.bind(promise);\n result.catch = promise.catch.bind(promise, undefined);\n return result;\n }\n\n onDisconnect(): OnDisconnect {\n _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n return new OnDisconnect(\n new ModularOnDisconnect(this._delegate._repo, this._delegate._path)\n );\n }\n\n get key(): string | null {\n return this.getKey();\n }\n\n get parent(): Reference | null {\n return this.getParent();\n }\n\n get root(): Reference {\n return this.getRoot();\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorPrefix as errorPrefixFxn } from '@firebase/util';\n\nexport const validateBoolean = function (\n fnName: string,\n argumentName: string,\n bool: unknown,\n optional: boolean\n) {\n if (optional && bool === undefined) {\n return;\n }\n if (typeof bool !== 'boolean') {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateEventType = function (\n fnName: string,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) {\n return;\n }\n\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(\n errorPrefixFxn(fnName, 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n forceLongPolling,\n forceWebSockets,\n goOnline,\n connectDatabaseEmulator,\n goOffline,\n ref,\n refFromURL,\n increment,\n serverTimestamp,\n Database as ModularDatabase\n} from '@firebase/database';\nimport {\n validateArgCount,\n Compat,\n EmulatorMockTokenOptions\n} from '@firebase/util';\n\nimport { Reference } from './Reference';\n\n/**\n * Class representing a firebase database.\n */\nexport class Database implements FirebaseService, Compat<ModularDatabase> {\n static readonly ServerValue = {\n TIMESTAMP: serverTimestamp(),\n increment: (delta: number) => increment(delta)\n };\n\n /**\n * The constructor should not be called by users of our public API.\n */\n constructor(readonly _delegate: ModularDatabase, readonly app: FirebaseApp) {}\n\n INTERNAL = {\n delete: () => this._delegate._delete(),\n forceWebSockets,\n forceLongPolling\n };\n\n /**\n * Modify this instance to communicate with the Realtime Database emulator.\n *\n * <p>Note: This method must be called before performing any other operation.\n *\n * @param host - the emulator host (ex: localhost)\n * @param port - the emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions;\n } = {}\n ): void {\n connectDatabaseEmulator(this._delegate, host, port, options);\n }\n\n /**\n * Returns a reference to the root or to the path specified in the provided\n * argument.\n *\n * @param path - The relative string path or an existing Reference to a database\n * location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @returns Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference) {\n const childRef = refFromURL(this._delegate, path.toString());\n return new Reference(this, childRef);\n } else {\n const childRef = ref(this._delegate, path);\n return new Reference(this, childRef);\n }\n }\n\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @returns Firebase reference.\n */\n refFromURL(url: string): Reference {\n const apiName = 'database.refFromURL';\n validateArgCount(apiName, 1, 1, arguments.length);\n const childRef = refFromURL(this._delegate, url);\n return new Reference(this, childRef);\n }\n\n // Make individual repo go offline.\n goOffline(): void {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n return goOffline(this._delegate);\n }\n\n goOnline(): void {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n return goOnline(this._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase, { FirebaseNamespace } from '@firebase/app-compat';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { enableLogging } from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { name, version } from '../package.json';\nimport { Database } from '../src/api/Database';\nimport * as INTERNAL from '../src/api/internal';\nimport { DataSnapshot, Query, Reference } from '../src/api/Reference';\n\nconst ServerValue = Database.ServerValue;\n\nexport function registerDatabase(instance: FirebaseNamespace) {\n // Register the Database Service with the 'firebase' namespace.\n (instance as unknown as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'database-compat',\n (container, { instanceIdentifier: url }) => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const databaseExp = container\n .getProvider('database')\n .getImmediate({ identifier: url });\n return new Database(databaseExp, app);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps(\n // firebase.database namespace properties\n {\n Reference,\n Query,\n Database,\n DataSnapshot,\n enableLogging,\n INTERNAL,\n ServerValue\n }\n )\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterDatabase(firebase);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n database?: {\n (app?: FirebaseApp): types.FirebaseDatabase;\n enableLogging: typeof types.enableLogging;\n ServerValue: types.ServerValue;\n Database: typeof types.FirebaseDatabase;\n };\n }\n interface FirebaseApp {\n database?(databaseURL?: string): types.FirebaseDatabase;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\nimport {\n _repoManagerDatabaseFromApp,\n _setSDKVersion\n} from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { Database } from './Database';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nexport function initStandalone<T>({\n app,\n url,\n version,\n customAuthImpl,\n namespace,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n namespace: T;\n nodeAdmin?: boolean;\n}): {\n instance: types.Database;\n namespace: T;\n} {\n _setSDKVersion(version);\n\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const authProvider = new Provider<FirebaseAuthInternalName>(\n 'auth-internal',\n new ComponentContainer('database-standalone')\n );\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n return {\n instance: new Database(\n _repoManagerDatabaseFromApp(\n app,\n authProvider,\n /* appCheckProvider= */ undefined,\n url,\n nodeAdmin\n ),\n app\n ) as types.Database,\n namespace\n };\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @provideGoog\n */\n\n\n/**\n * @define {boolean} Overridden to true by the compiler.\n */\nvar COMPILED = false;\n\n\n/**\n * Base namespace for the Closure library. Checks to see goog is already\n * defined in the current scope before assigning to prevent clobbering if\n * base.js is loaded more than once.\n *\n * @const\n */\nvar goog = goog || {};\n\n/**\n * Reference to the global object.\n * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n *\n * More info on this implementation here:\n * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n *\n * @const\n * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n * @type {!Global}\n */\ngoog.global =\n // Check `this` first for backwards compatibility.\n // Valid unless running as an ES module or in a function wrapper called\n // without setting `this` properly.\n // Note that base.js can't usefully be imported as an ES module, but it may\n // be compiled into bundles that are loadable as ES modules.\n this ||\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/self\n // For in-page browser environments and workers.\n self;\n\n\n/**\n * A hook for overriding the define values in uncompiled mode.\n *\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\n * `goog.define` will use the value instead of the default value. This\n * allows flags to be overwritten without compilation (this is normally\n * accomplished with the compiler's \"define\" flag).\n *\n * Example:\n * <pre>\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\n\n\n/**\n * A hook for overriding the define values in uncompiled or compiled mode,\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\n *\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\n * string literals or the compiler will emit an error.\n *\n * While any @define value may be set, only those set with goog.define will be\n * effective for uncompiled code.\n *\n * Example:\n * <pre>\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\n * </pre>\n *\n * Currently the Closure Compiler will only recognize very simple definitions of\n * this value when looking for values to apply to compiled code and ignore all\n * other references. Specifically, it looks the value defined at the variable\n * declaration, as with the example above.\n *\n * TODO(user): Improve the recognized definitions.\n *\n * @type {!Object<string, (string|number|boolean)>|null|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name The name of the object that this file defines.\n * @param {*=} object The object to expose at the end of the path.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether object should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @param {?Object=} objectToExportTo The object to add the path to; if this\n * field is not specified, its value defaults to `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, object, overwriteImplicit, objectToExportTo) {\n var parts = name.split('.');\n var cur = objectToExportTo || goog.global;\n\n // Internet Explorer exhibits strange behavior when throwing errors from\n // methods externed in this manner. See the testExportSymbolExceptions in\n // base_test.html for an example.\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\n cur.execScript('var ' + parts[0]);\n }\n\n for (var part; parts.length && (part = parts.shift());) {\n if (!parts.length && object !== undefined) {\n if (!overwriteImplicit && goog.isObject(object) &&\n goog.isObject(cur[part])) {\n // Merge properties on object (the input parameter) with the existing\n // implicitly defined namespace, so as to not clobber previously\n // defined child namespaces.\n for (var prop in object) {\n if (object.hasOwnProperty(prop)) {\n cur[part][prop] = object[prop];\n }\n }\n } else {\n // Either there is no existing implicit namespace, or overwriteImplicit\n // is set to true, so directly assign object (the input parameter) to\n // the namespace.\n cur[part] = object;\n }\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\n cur = cur[part];\n } else {\n cur = cur[part] = {};\n }\n }\n};\n\n\n/**\n * Defines a named value. In uncompiled mode, the value is retrieved from\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n * has the property specified, and otherwise used the defined defaultValue.\n * When compiled the default can be overridden using the compiler options or the\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n * can be used safely in modules. Note that the value type MUST be either\n * boolean, number, or string.\n *\n * @param {string} name The distinguished name to provide.\n * @param {T} defaultValue\n * @return {T} The defined value.\n * @template T\n */\ngoog.define = function(name, defaultValue) {\n var value = defaultValue;\n if (!COMPILED) {\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\n var defines = goog.global.CLOSURE_DEFINES;\n if (uncompiledDefines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\n value = uncompiledDefines[name];\n } else if (\n defines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (defines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(defines, name)) {\n value = defines[name];\n }\n }\n return value;\n};\n\n\n/**\n * @define {number} Integer year indicating the set of browser features that are\n * guaranteed to be present. This is defined to include exactly features that\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\n * specified year. For example,\n * ```js\n * if (goog.FEATURESET_YEAR >= 2019) {\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\n * } else {\n * // polyfill for older browsers\n * }\n * ```\n * This is intended to be the primary define for removing\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\n * and should inform the default value for most other defines:\n * ```js\n * const ASSUME_NATIVE_PROMISE =\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\n * ```\n *\n * The default assumption is that IE9 is the lowest supported browser, which was\n * first available Jan 1, 2012.\n *\n * TODO(user): Reference more thorough documentation when it's available.\n */\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\n\n\n/**\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\n * that should not be included in a production. It can be easily stripped\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n * JSCompiler. For example, most toString() methods should be declared inside an\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n * purposes and it is difficult for the JSCompiler to statically determine\n * whether they are used.\n */\ngoog.DEBUG = goog.define('goog.DEBUG', true);\n\n\n/**\n * @define {string} LOCALE defines the locale being used for compilation. It is\n * used to select locale specific data to be compiled in js binary. BUILD rule\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\n * option.\n *\n * Take into account that the locale code format is important. You should use\n * the canonical Unicode format with hyphen as a delimiter. Language must be\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\n *\n * See more info about locale codes here:\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\n *\n * For language codes you should use values defined by ISO 693-1. See it here\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\n * be used instead of the new code (he).\n *\n */\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\n\n\n/**\n * This method is intended to be used for bookkeeping purposes. We would\n * like to distinguish uses of goog.LOCALE used for code stripping purposes\n * and uses of goog.LOCALE for other uses (such as URL parameters).\n *\n * This allows us to ban direct uses of goog.LOCALE and to ensure that all\n * code has been transformed to our new localization build scheme.\n *\n * @return {string}\n *\n */\ngoog.getLocale = function() {\n return goog.LOCALE;\n};\n\n\n/**\n * @define {boolean} Whether this code is running on trusted sites.\n *\n * On untrusted sites, several native functions can be defined or overridden by\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\n * to false forces closure to use its own implementations when possible.\n *\n * If your JavaScript can be loaded by a third party site and you are wary about\n * relying on non-standard implementations, specify\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\n */\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\n\n\n/**\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\n * be disallowed in the compilation unit.\n */\ngoog.DISALLOW_TEST_ONLY_CODE =\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\n\n\n/**\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\n * loading scripts via goog.require. @see appendScriptSrcNode_.\n */\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\n\n\n/**\n * Defines a namespace in Closure.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * The presence of one or more goog.provide() calls in a file indicates\n * that the file defines the given objects/namespaces.\n * Provided symbols must not be null or undefined.\n *\n * In addition, goog.provide() creates the object stubs for a namespace\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\n * goog.foo.bar if it does not already exist).\n *\n * Build tools also scan for provide/require/module statements\n * to discern dependencies, build dependency files (see deps.js), etc.\n *\n * @see goog.require\n * @see goog.module\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * deprecated Use goog.module (see b/159289405)\n */\ngoog.provide = function(name) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.provide cannot be used within a module.');\n }\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n }\n\n goog.constructNamespace_(name);\n};\n\n\n/**\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * @param {?Object=} object The object to embed in the namespace.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether opt_obj should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @private\n */\ngoog.constructNamespace_ = function(name, object, overwriteImplicit) {\n if (!COMPILED) {\n delete goog.implicitNamespaces_[name];\n\n var namespace = name;\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\n if (goog.getObjectByName(namespace)) {\n break;\n }\n goog.implicitNamespaces_[namespace] = true;\n }\n }\n\n goog.exportPath_(name, object, overwriteImplicit);\n};\n\n\n/**\n * According to the CSP3 spec a nonce must be a valid base64 string.\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\n * @private @const\n */\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\n * Defaults to global context.\n * @return {string} CSP nonce or empty string if no nonce is present.\n * @private\n */\ngoog.getScriptNonce_ = function(opt_window) {\n var doc = (opt_window || goog.global).document;\n var script = doc.querySelector && doc.querySelector('script[nonce]');\n if (script) {\n // Try to get the nonce from the IDL property first, because browsers that\n // implement additional nonce protection features (currently only Chrome) to\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\n // See https://github.com/whatwg/html/issues/2369\n var nonce = script['nonce'] || script.getAttribute('nonce');\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n return nonce;\n }\n }\n return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n * restrictions are intended to leave the door open for using goog.require\n * with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n if (typeof name !== 'string' || !name ||\n name.search(goog.VALID_MODULE_RE_) == -1) {\n throw new Error('Invalid module identifier');\n }\n if (!goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\n 'module. For more info see: ' +\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n }\n if (goog.moduleLoaderState_.moduleName) {\n throw new Error('goog.module may only be called once per module.');\n }\n\n // Store the module name for the loader.\n goog.moduleLoaderState_.moduleName = name;\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n delete goog.implicitNamespaces_[name];\n }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n if (!COMPILED) {\n if (name in goog.loadedModules_) {\n return goog.loadedModules_[name].exports;\n } else if (!goog.implicitNamespaces_[name]) {\n var ns = goog.getObjectByName(name);\n return ns != null ? ns : null;\n }\n }\n return null;\n};\n\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n ES6: 'es6',\n GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n * moduleName: (string|undefined),\n * declareLegacyNamespace:boolean,\n * type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n * initialized.\n */\ngoog.isInModuleLoader_ = function() {\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n return !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n var inLoader = !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n if (inLoader) {\n return true;\n }\n\n var jscomp = goog.global['$jscomp'];\n\n if (jscomp) {\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\n // that has some of the runtime, but not all of it. This can happen if\n // optimizations are turned on so the unused runtime is removed but renaming\n // and Closure pass are off (so $jscomp is still named $jscomp and the\n // goog.provide/require calls still exist).\n if (typeof jscomp.getCurrentModulePath != 'function') {\n return false;\n }\n\n // Bundled ES6 module.\n return !!jscomp.getCurrentModulePath();\n }\n\n return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name. This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'goog.module.declareLegacyNamespace must be called from ' +\n 'within a goog.module');\n }\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.module must be called prior to ' +\n 'goog.module.declareLegacyNamespace.');\n }\n goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n if (!COMPILED) {\n if (!goog.isInEs6ModuleLoader_()) {\n throw new Error(\n 'goog.declareModuleId may only be called from ' +\n 'within an ES6 module');\n }\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.declareModuleId may only be called once per module.');\n }\n if (namespace in goog.loadedModules_) {\n throw new Error(\n 'Module with namespace \"' + namespace + '\" already exists.');\n }\n }\n if (goog.moduleLoaderState_) {\n // Not bundled - debug loading.\n goog.moduleLoaderState_.moduleName = namespace;\n } else {\n // Bundled - not debug loading, no module loader state.\n var jscomp = goog.global['$jscomp'];\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n throw new Error(\n 'Module with namespace \"' + namespace +\n '\" has been loaded incorrectly.');\n }\n var exports = jscomp.require(jscomp.getCurrentModulePath());\n goog.loadedModules_[namespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: namespace\n };\n }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n * raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n if (goog.DISALLOW_TEST_ONLY_CODE) {\n opt_message = opt_message || '';\n throw new Error(\n 'Importing test-only code into non-debug environment' +\n (opt_message ? ': ' + opt_message : '.'));\n }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n * \"goog.package.part\".\n * @deprecated See go/noforwarddeclaration, Use `goog.requireType` instead.\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n /**\n * Check if the given name has been goog.provided. This will return false for\n * names that are available only as implicit namespaces.\n * @param {string} name name of the object to look for.\n * @return {boolean} Whether the name has been provided.\n * @private\n */\n goog.isProvided_ = function(name) {\n return (name in goog.loadedModules_) ||\n (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n };\n\n /**\n * Namespaces implicitly defined by goog.provide. For example,\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n * 'goog.events' must be namespaces.\n *\n * @type {!Object<string, (boolean|undefined)>}\n * @private\n */\n goog.implicitNamespaces_ = {'goog.module': true};\n\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n // here and because the existing module package has not been moved yet out of\n // the goog.module namespace. This satisifies both the debug loader and\n // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name. The object\n * is not found if null or undefined. If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n * |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n var parts = name.split('.');\n var cur = opt_obj || goog.global;\n for (var i = 0; i < parts.length; i++) {\n cur = cur[parts[i]];\n if (cur == null) {\n return null;\n }\n }\n return cur;\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n * the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n * the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n * how the file must be loaded. The boolean 'true' is equivalent\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n }\n};\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development. The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script. If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js. Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', true);\n\n\n/**\n * @param {string} msg\n * @private\n */\ngoog.logToConsole_ = function(msg) {\n if (goog.global.console) {\n goog.global.console['error'](msg);\n }\n};\n\n\n/**\n * Implements a system for the dynamic resolution of dependencies that works in\n * parallel with the BUILD system.\n *\n * Note that all calls to goog.require will be stripped by the compiler.\n *\n * @see goog.provide\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?} If called within a goog.module or ES6 module file, the associated\n * namespace or module otherwise null.\n */\ngoog.require = function(namespace) {\n if (!COMPILED) {\n // Might need to lazy load on old IE.\n if (goog.ENABLE_DEBUG_LOADER) {\n goog.debugLoader_.requested(namespace);\n }\n\n // If the object already exists we do not need to do anything.\n if (goog.isProvided_(namespace)) {\n if (goog.isInModuleLoader_()) {\n return goog.module.getInternal_(namespace);\n }\n } else if (goog.ENABLE_DEBUG_LOADER) {\n var moduleLoaderState = goog.moduleLoaderState_;\n goog.moduleLoaderState_ = null;\n try {\n goog.debugLoader_.load_(namespace);\n } finally {\n goog.moduleLoaderState_ = moduleLoaderState;\n }\n }\n\n return null;\n }\n};\n\n\n/**\n * Requires a symbol for its type information. This is an indication to the\n * compiler that the symbol may appear in type annotations, yet it is not\n * referenced at runtime.\n *\n * When called within a goog.module or ES6 module file, the return value may be\n * assigned to or destructured into a variable, but it may not be otherwise used\n * in code outside of a type annotation.\n *\n * Note that all calls to goog.requireType will be stripped by the compiler.\n *\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?}\n */\ngoog.requireType = function(namespace) {\n // Return an empty object so that single-level destructuring of the return\n // value doesn't crash at runtime when using the debug loader. Multi-level\n // destructuring isn't supported.\n return {};\n};\n\n\n/**\n * Path for included scripts.\n * @type {string}\n */\ngoog.basePath = '';\n\n\n/**\n * A hook for overriding the base path.\n * @type {string|undefined}\n */\ngoog.global.CLOSURE_BASE_PATH;\n\n\n/**\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\n * deps files will attempt to be loaded.\n * @type {boolean|undefined}\n */\ngoog.global.CLOSURE_NO_DEPS;\n\n\n/**\n * A function to import a single script. This is meant to be overridden when\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\n * in the global scope so that it can be set before base.js is loaded, which\n * allows deps.js to be imported properly.\n *\n * The first parameter the script source, which is a relative URI. The second,\n * optional parameter is the script contents, in the event the script needed\n * transformation. It should return true if the script was imported, false\n * otherwise.\n * @type {(function(string, string=): boolean)|undefined}\n */\ngoog.global.CLOSURE_IMPORT_SCRIPT;\n\n\n/**\n * Null function used for default values of callbacks, etc.\n * @return {void} Nothing.\n * @deprecated use '()=>{}' or 'function(){}' instead.\n */\ngoog.nullFunction = function() {};\n\n\n/**\n * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n * code. See\n * https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n * method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n * but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n // instance_ is immediately set to prevent issues with sealed constructors\n // such as are encountered when a constructor is returned as the export object\n // of a goog.module in unoptimized code.\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n /** @type {undefined|!Object} @suppress {underscore} */\n ctor.instance_ = undefined;\n ctor.getInstance = function() {\n if (ctor.instance_) {\n return ctor.instance_;\n }\n if (goog.DEBUG) {\n // NOTE: JSCompiler can't optimize away Array#push.\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n }\n // Cast to avoid conformance violations that ctor.instance_ is unknown\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader. This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile. Valid values\n * are 'always', 'never', and 'detect'. The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} If a file needs to be transpiled what the output language\n * should be. By default this is the highest language level this file detects\n * the current environment supports. Generally this flag should not be set, but\n * it could be useful to override. Example: If the current environment supports\n * ES6 then by default ES7+ files will be transpiled to ES6, unless this is\n * overridden.\n *\n * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized\n * is treated as es3.\n *\n * Note that setting this value does not force transpilation. Just if\n * transpilation occurs this will be the output. So this is most useful when\n * goog.TRANSPILE is set to 'always' and then forcing the language level to be\n * something lower than what the environment detects.\n */\ngoog.TRANSPILE_TO_LANGUAGE = goog.define('goog.TRANSPILE_TO_LANGUAGE', '');\n\n\n/**\n * @define {string} Path to the transpiler. Executing the script at this\n * path (relative to base.js) should define a function $jscomp.transpile.\n */\ngoog.TRANSPILER = goog.define('goog.TRANSPILER', 'transpile.js');\n\n\n/**\n * @define {string} Trusted Types policy name. If non-empty then Closure will\n * use Trusted Types.\n */\ngoog.TRUSTED_TYPES_POLICY_NAME =\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', 'goog');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\n\n\n/**\n * @param {function(?):?|string} moduleDef The module definition.\n */\ngoog.loadModule = function(moduleDef) {\n // NOTE: we allow function definitions to be either in the from\n // of a string to eval (which keeps the original source intact) or\n // in a eval forbidden environment (CSP) we allow a function definition\n // which in its body must call `goog.module`, and return the exports\n // of the module.\n var previousState = goog.moduleLoaderState_;\n try {\n goog.moduleLoaderState_ = {\n moduleName: '',\n declareLegacyNamespace: false,\n type: goog.ModuleType.GOOG\n };\n var origExports = {};\n var exports = origExports;\n if (typeof moduleDef === 'function') {\n exports = moduleDef.call(undefined, exports);\n } else if (typeof moduleDef === 'string') {\n exports = goog.loadModuleFromSource_.call(undefined, exports, moduleDef);\n } else {\n throw new Error('Invalid module definition');\n }\n\n var moduleName = goog.moduleLoaderState_.moduleName;\n if (typeof moduleName === 'string' && moduleName) {\n // Don't seal legacy namespaces as they may be used as a parent of\n // another namespace\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\n // Whether exports was overwritten via default export assignment.\n // This is important for legacy namespaces as it dictates whether\n // previously a previously loaded implicit namespace should be clobbered\n // or not.\n var isDefaultExport = origExports !== exports;\n goog.constructNamespace_(moduleName, exports, isDefaultExport);\n } else if (\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\n typeof exports == 'object' && exports != null) {\n Object.seal(exports);\n }\n\n var data = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: goog.moduleLoaderState_.moduleName\n };\n goog.loadedModules_[moduleName] = data;\n } else {\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\n }\n } finally {\n goog.moduleLoaderState_ = previousState;\n }\n};\n\n\n/**\n * @private @const\n */\ngoog.loadModuleFromSource_ =\n /** @type {function(!Object, string):?} */ (function(exports) {\n // NOTE: we avoid declaring parameters or local variables here to avoid\n // masking globals or leaking values into the module definition.\n 'use strict';\n eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(arguments[1]));\n return exports;\n });\n\n\n/**\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\n * path components.\n * @param {string} path\n * @return {string}\n * @private\n */\ngoog.normalizePath_ = function(path) {\n var components = path.split('/');\n var i = 0;\n while (i < components.length) {\n if (components[i] == '.') {\n components.splice(i, 1);\n } else if (\n i && components[i] == '..' && components[i - 1] &&\n components[i - 1] != '..') {\n components.splice(--i, 2);\n } else {\n i++;\n }\n }\n return components.join('/');\n};\n\n\n/**\n * Provides a hook for loading a file when using Closure's goog.require() API\n * with goog.modules. In particular this hook is provided to support Node.js.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\n\n\n/**\n * Loads file by synchronous XHR. Should not be used in production environments.\n * @param {string} src Source URL.\n * @return {?string} File contents, or null if load failed.\n * @private\n */\ngoog.loadFileSync_ = function(src) {\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\n } else {\n try {\n /** @type {XMLHttpRequest} */\n var xhr = new goog.global['XMLHttpRequest']();\n xhr.open('get', src, false);\n xhr.send();\n // NOTE: Successful http: requests have a status of 200, but successful\n // file: requests may have a status of zero. Any other status, or a\n // thrown exception (particularly in case of file: requests) indicates\n // some sort of error, which we treat as a missing or unavailable file.\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\n } catch (err) {\n // No need to rethrow or log, since errors should show up on their own.\n return null;\n }\n }\n};\n\n\n/**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @param {string} target Language level output.\n * @return {string} The transpiled code.\n * @private\n */\ngoog.transpile_ = function(code, path, target) {\n var jscomp = goog.global['$jscomp'];\n if (!jscomp) {\n goog.global['$jscomp'] = jscomp = {};\n }\n var transpile = jscomp.transpile;\n if (!transpile) {\n var transpilerPath = goog.basePath + goog.TRANSPILER;\n var transpilerCode = goog.loadFileSync_(transpilerPath);\n if (transpilerCode) {\n // This must be executed synchronously, since by the time we know we\n // need it, we're about to load and write the ES6 code synchronously,\n // so a normal script-tag load will be too slow. Wrapped in a function\n // so that code is eval'd in the global scope.\n (function() {\n (0, eval)(transpilerCode + '\\n//# sourceURL=' + transpilerPath);\n }).call(goog.global);\n // Even though the transpiler is optional, if $gwtExport is found, it's\n // a sign the transpiler was loaded and the $jscomp.transpile *should*\n // be there.\n if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&\n !goog.global['$gwtExport']['$jscomp']['transpile']) {\n throw new Error(\n 'The transpiler did not properly export the \"transpile\" ' +\n 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));\n }\n // transpile.js only exports a single $jscomp function, transpile. We\n // grab just that and add it to the existing definition of $jscomp which\n // contains the polyfills.\n goog.global['$jscomp'].transpile =\n goog.global['$gwtExport']['$jscomp']['transpile'];\n jscomp = goog.global['$jscomp'];\n transpile = jscomp.transpile;\n }\n }\n if (!transpile) {\n // The transpiler is an optional component. If it's not available then\n // replace it with a pass-through function that simply logs.\n var suffix = ' requires transpilation but no transpiler was found.';\n transpile = jscomp.transpile = function(code, path) {\n // TODO(sdh): figure out some way to get this error to show up\n // in test results, noting that the failure may occur in many\n // different ways, including in loadModule() before the test\n // runner even comes up.\n goog.logToConsole_(path + suffix);\n return code;\n };\n }\n // Note: any transpilation errors/warnings will be logged to the console.\n return transpile(code, path, target);\n};\n\n//==============================================================================\n// Language Enhancements\n//==============================================================================\n\n\n/**\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\n * operator in such a way that null returns 'null' and arrays return 'array'.\n * @param {?} value The value to get the type of.\n * @return {string} The name of the type.\n */\ngoog.typeOf = function(value) {\n var s = typeof value;\n\n if (s != 'object') {\n return s;\n }\n\n if (!value) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return 'array';\n }\n return s;\n};\n\n\n/**\n * Returns true if the object looks like an array. To qualify as array like\n * the value needs to be either a NodeList or an object with a Number length\n * property. Note that for this function neither strings nor functions are\n * considered \"array-like\".\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArrayLike = function(val) {\n var type = goog.typeOf(val);\n // We do not use goog.isObject here in order to exclude function values.\n return type == 'array' || type == 'object' && typeof val.length == 'number';\n};\n\n\n/**\n * Returns true if the object looks like a Date. To qualify as Date-like the\n * value needs to be an object and have a getFullYear() function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a like a Date.\n */\ngoog.isDateLike = function(val) {\n return goog.isObject(val) && typeof val.getFullYear == 'function';\n};\n\n\n/**\n * Returns true if the specified value is an object. This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n var type = typeof val;\n return type == 'object' && val != null || type == 'function';\n // return Object(val) === val also works, but is slower, especially if val is\n // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n return Object.prototype.hasOwnProperty.call(obj, goog.UID_PROPERTY_) &&\n obj[goog.UID_PROPERTY_] ||\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n\n // In IE, DOM nodes are not instances of Object and throw an exception if we\n // try to delete. Instead we try to use removeAttribute.\n if (obj !== null && 'removeAttribute' in obj) {\n obj.removeAttribute(goog.UID_PROPERTY_);\n }\n\n try {\n delete obj[goog.UID_PROPERTY_];\n } catch (ex) {\n }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\n * refer to themselves will cause infinite recursion.\n *\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\n * UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {*} obj The value to clone.\n * @return {*} A clone of the input value.\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\n */\ngoog.cloneObject = function(obj) {\n var type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (typeof obj.clone === 'function') {\n return obj.clone();\n }\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n }\n var clone = type == 'array' ? [] : {};\n for (var key in obj) {\n clone[key] = goog.cloneObject(obj[key]);\n }\n return clone;\n }\n\n return obj;\n};\n\n\n/**\n * A native implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindNative_ = function(fn, selfObj, var_args) {\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\n};\n\n\n/**\n * A pure-JS implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindJs_ = function(fn, selfObj, var_args) {\n if (!fn) {\n throw new Error();\n }\n\n if (arguments.length > 2) {\n var boundArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n // Prepend the bound arguments to the current arguments.\n var newArgs = Array.prototype.slice.call(arguments);\n Array.prototype.unshift.apply(newArgs, boundArgs);\n return fn.apply(selfObj, newArgs);\n };\n\n } else {\n return function() {\n return fn.apply(selfObj, arguments);\n };\n }\n};\n\n\n/**\n * Partially applies this function to a particular 'this object' and zero or\n * more arguments. The result is a new function with some arguments of the first\n * function pre-filled and the value of this 'pre-specified'.\n *\n * Remaining arguments specified at call-time are appended to the pre-specified\n * ones.\n *\n * Also see: {@link #partial}.\n *\n * Usage:\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\n * barMethBound('arg3', 'arg4');</pre>\n *\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @suppress {deprecated} See above.\n * @deprecated use `=> {}` or Function.prototype.bind instead.\n */\ngoog.bind = function(fn, selfObj, var_args) {\n // TODO(nicksantos): narrow the type signature.\n if (Function.prototype.bind &&\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\n // extension environment. This means that for Chrome extensions, they get\n // the implementation of Function.prototype.bind that calls goog.bind\n // instead of the native one. Even worse, we don't want to introduce a\n // circular dependency between goog.bind and Function.prototype.bind, so\n // we have to hack this to make sure it works correctly.\n Function.prototype.bind.toString().indexOf('native code') != -1) {\n goog.bind = goog.bindNative_;\n } else {\n goog.bind = goog.bindJs_;\n }\n return goog.bind.apply(null, arguments);\n};\n\n\n/**\n * Like goog.bind(), except that a 'this object' is not required. Useful when\n * the target function is already bound.\n *\n * Usage:\n * var g = goog.partial(f, arg1, arg2);\n * g(arg3, arg4);\n *\n * @param {Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.partial = function(fn, var_args) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function() {\n // Clone the array (with slice()) and append additional arguments\n // to the existing arguments.\n var newArgs = args.slice();\n newArgs.push.apply(newArgs, arguments);\n return fn.apply(/** @type {?} */ (this), newArgs);\n };\n};\n\n\n/**\n * Copies all the members of a source object to a target object. This method\n * does not work on all browsers for all objects that contain keys such as\n * toString or hasOwnProperty. Use goog.object.extend for this purpose.\n *\n * NOTE: Some have advocated for the use of goog.mixin to setup classes\n * with multiple inheritence (traits, mixins, etc). However, as it simply\n * uses \"for in\", this is not compatible with ES6 classes whose methods are\n * non-enumerable. Changing this, would break cases where non-enumerable\n * properties are not expected.\n *\n * @param {Object} target Target.\n * @param {Object} source Source.\n * @deprecated Prefer Object.assign\n */\ngoog.mixin = function(target, source) {\n for (var x in source) {\n target[x] = source[x];\n }\n\n // For IE7 or lower, the for-in-loop does not contain any properties that are\n // not enumerable on the prototype object (for example, isPrototypeOf from\n // Object.prototype) but also it will not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n};\n\n\n/**\n * @return {number} An integer value representing the number of milliseconds\n * between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = function() {\n return Date.now();\n};\n\n\n/**\n * Evals JavaScript in the global scope.\n *\n * Throws an exception if neither execScript or eval is defined.\n * @param {string|!TrustedScript} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n (0, eval)(script);\n};\n\n\n/**\n * Optional map of CSS class names to obfuscated names used with\n * goog.getCssName().\n * @private {!Object<string, string>|undefined}\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMapping_;\n\n\n/**\n * Optional obfuscation style for CSS class names. Should be set to either\n * 'BY_WHOLE' or 'BY_PART' if defined.\n * @type {string|undefined}\n * @private\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMappingStyle_;\n\n\n\n/**\n * A hook for modifying the default behavior goog.getCssName. The function\n * if present, will receive the standard output of the goog.getCssName as\n * its input.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\n\n\n/**\n * Handles strings that are intended to be used as CSS class names.\n *\n * This function works in tandem with @see goog.setCssNameMapping.\n *\n * Without any mapping set, the arguments are simple joined with a hyphen and\n * passed through unaltered.\n *\n * When there is a mapping, there are two possible styles in which these\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n * style, the full css name is looked up in the map directly. If a rewrite is\n * not specified by the map, the compiler will output a warning.\n *\n * When the mapping is passed to the compiler, it will replace calls to\n * goog.getCssName with the strings from the mapping, e.g.\n * var x = goog.getCssName('foo');\n * var y = goog.getCssName(this.baseClass, 'active');\n * becomes:\n * var x = 'foo';\n * var y = this.baseClass + '-active';\n *\n * If one argument is passed it will be processed, if two are passed only the\n * modifier will be processed, as it is assumed the first argument was generated\n * as a result of calling goog.getCssName.\n *\n * @param {string} className The class name.\n * @param {string=} opt_modifier A modifier to be appended to the class name.\n * @return {string} The class name or the concatenation of the class name and\n * the modifier.\n */\ngoog.getCssName = function(className, opt_modifier) {\n // String() is used for compatibility with compiled soy where the passed\n // className can be non-string objects.\n if (String(className).charAt(0) == '.') {\n throw new Error(\n 'className passed in goog.getCssName must not start with \".\".' +\n ' You passed: ' + className);\n }\n\n var getMapping = function(cssName) {\n return goog.cssNameMapping_[cssName] || cssName;\n };\n\n var renameByParts = function(cssName) {\n // Remap all the parts individually.\n var parts = cssName.split('-');\n var mapped = [];\n for (var i = 0; i < parts.length; i++) {\n mapped.push(getMapping(parts[i]));\n }\n return mapped.join('-');\n };\n\n var rename;\n if (goog.cssNameMapping_) {\n rename =\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\n } else {\n rename = function(a) {\n return a;\n };\n }\n\n var result =\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\n\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\n // processing of the class name.\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\n }\n\n return result;\n};\n\n\n/**\n * Sets the map to check when returning a value from goog.getCssName(). Example:\n * <pre>\n * goog.setCssNameMapping({\n * \"goog\": \"a\",\n * \"disabled\": \"b\",\n * });\n *\n * var x = goog.getCssName('goog');\n * // The following evaluates to: \"a a-b\".\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n * </pre>\n * When declared as a map of string literals to string literals, the JSCompiler\n * will replace all calls to goog.getCssName() using the supplied map if the\n * --process_closure_primitives flag is set.\n *\n * @param {!Object} mapping A map of strings to strings where keys are possible\n * arguments to goog.getCssName() and values are the corresponding values\n * that should be returned.\n * @param {string=} opt_style The style of css name mapping. There are two valid\n * options: 'BY_PART', and 'BY_WHOLE'.\n * @see goog.getCssName for a description.\n */\ngoog.setCssNameMapping = function(mapping, opt_style) {\n goog.cssNameMapping_ = mapping;\n goog.cssNameMappingStyle_ = opt_style;\n};\n\n\n/**\n * To use CSS renaming in compiled mode, one of the input files should have a\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\n * mode, JavaScript code should be loaded before this base.js file that declares\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\n * are made in uncompiled mode.\n *\n * A hook for overriding the CSS name mapping.\n * @type {!Object<string, string>|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\n\n\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\n // This does not call goog.setCssNameMapping() because the JSCompiler\n // requires that goog.setCssNameMapping() be called with an object literal.\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\n}\n\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {Object<string, string>=} opt_values Maps place holder name to value.\n * @param {{html: (boolean|undefined),\n * unescapeHtmlEntities: (boolean|undefined)}=} opt_options Options:\n * html: Escape '<' in str to '&lt;'. Used by Closure Templates where the\n * generated code size and performance is critical which is why {@link\n * goog.html.SafeHtmlFormatter} is not used. The value must be literal true\n * or false.\n * unescapeHtmlEntities: Unescape common html entities: &gt;, &lt;, &apos;,\n * &quot; and &amp;. Used for messages not in HTML context, such as with\n * `textContent` property.\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n if (opt_options && opt_options.html) {\n // Note that '&' is not replaced because the translation can contain HTML\n // entities.\n str = str.replace(/</g, '&lt;');\n }\n if (opt_options && opt_options.unescapeHtmlEntities) {\n // Note that \"&amp;\" must be the last to avoid \"creating\" new entities.\n str = str.replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&apos;/g, '\\'')\n .replace(/&quot;/g, '\"')\n .replace(/&amp;/g, '&');\n }\n if (opt_values) {\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n return (opt_values != null && key in opt_values) ? opt_values[key] :\n match;\n });\n }\n return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n * public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n * Foo.prototype.myMethod);\n * new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {?Object=} objectToExportTo The object to add the path to; default\n * is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, objectToExportTo) {\n goog.exportPath_(\n publicPath, object, /* overwriteImplicit= */ true, objectToExportTo);\n};\n\n\n/**\n * Exports a property unobfuscated into the object's namespace.\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n * @param {Object} object Object whose static property is being exported.\n * @param {string} publicName Unobfuscated name to export.\n * @param {*} symbol Object the name should point to.\n */\ngoog.exportProperty = function(object, publicName, symbol) {\n object[publicName] = symbol;\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * Usage:\n * <pre>\n * function ParentClass(a, b) { }\n * ParentClass.prototype.foo = function(a) { };\n *\n * function ChildClass(a, b, c) {\n * ChildClass.base(this, 'constructor', a, b);\n * }\n * goog.inherits(ChildClass, ParentClass);\n *\n * var child = new ChildClass('a', 'b', 'see');\n * child.foo(); // This works.\n * </pre>\n *\n * @param {!Function} childCtor Child class.\n * @param {!Function} parentCtor Parent class.\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\n * Function.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {}\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n\n /**\n * Calls superclass constructor/method.\n *\n * This function is only available if you use goog.inherits to\n * express inheritance relationships between classes.\n *\n * NOTE: This is a replacement for goog.base and for superClass_\n * property defined in childCtor.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {string} methodName The method name to call. Calling\n * superclass constructor can be done with the special string\n * 'constructor'.\n * @param {...*} var_args The arguments to pass to superclass\n * method/constructor.\n * @return {*} The return value of the superclass method/constructor.\n */\n childCtor.base = function(me, methodName, var_args) {\n // Copying using loop to avoid deop due to passing arguments object to\n // function. This is faster in many JS engines as of late 2014.\n var args = new Array(arguments.length - 2);\n for (var i = 2; i < arguments.length; i++) {\n args[i - 2] = arguments[i];\n }\n return parentCtor.prototype[methodName].apply(me, args);\n };\n};\n\n\n/**\n * Allow for aliasing within scope functions. This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied. In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call. This function can contain aliases\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\n * (e.g. \"var Timer = goog.Timer\").\n * @deprecated Use goog.module instead.\n */\ngoog.scope = function(fn) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.scope is not supported within a module.');\n }\n fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n * eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n * - from the compiler's perspective, the instance returned from the\n * constructor is sealed (no new properties may be added). This enables\n * better checks.\n * - the compiler will rewrite this definition to a form that is optimal\n * for type checking and optimization (initially this will be a more\n * traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n * An object literal describing\n * the class. It may have the following properties:\n * \"constructor\": the constructor function\n * \"statics\": an object literal containing methods to add to the constructor\n * as \"static\" methods or a function that will receive the constructor\n * function as its only parameter to which static properties can\n * be added.\n * all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.defineClass = function(superClass, def) {\n // TODO(johnlenz): consider making the superClass an optional parameter.\n var constructor = def.constructor;\n var statics = def.statics;\n // Wrap the constructor prior to setting up the prototype and static methods.\n if (!constructor || constructor == Object.prototype.constructor) {\n constructor = function() {\n throw new Error(\n 'cannot instantiate an interface (no constructor defined).');\n };\n }\n\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\n if (superClass) {\n goog.inherits(cls, superClass);\n }\n\n // Remove all the properties that should not be copied to the prototype.\n delete def.constructor;\n delete def.statics;\n\n goog.defineClass.applyProperties_(cls.prototype, def);\n if (statics != null) {\n if (statics instanceof Function) {\n statics(cls);\n } else {\n goog.defineClass.applyProperties_(cls, statics);\n }\n }\n\n return cls;\n};\n\n\n/**\n * @typedef {{\n * constructor: (!Function|undefined),\n * statics: (Object|undefined|function(Function):void)\n * }}\n */\ngoog.defineClass.ClassDescriptor;\n\n\n/**\n * @define {boolean} Whether the instances returned by goog.defineClass should\n * be sealed when possible.\n *\n * When sealing is disabled the constructor function will not be wrapped by\n * goog.defineClass, making it incompatible with ES6 class methods.\n */\ngoog.defineClass.SEAL_CLASS_INSTANCES =\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\n\n\n/**\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\n * defined, this function will wrap the constructor in a function that seals the\n * results of the provided constructor function.\n *\n * @param {!Function} ctr The constructor whose results maybe be sealed.\n * @param {Function} superClass The superclass constructor.\n * @return {!Function} The replacement constructor.\n * @private\n */\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\n // Do now wrap the constructor when sealing is disabled. Angular code\n // depends on this for injection to work properly.\n return ctr;\n }\n\n // NOTE: The sealing behavior has been removed\n\n /**\n * @this {Object}\n * @return {?}\n */\n var wrappedCtr = function() {\n // Don't seal an instance of a subclass when it calls the constructor of\n // its super class as there is most likely still setup to do.\n var instance = ctr.apply(this, arguments) || this;\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\n\n return instance;\n };\n\n return wrappedCtr;\n};\n\n\n\n// TODO(johnlenz): share these values with the goog.object\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n * @private\n * @const\n */\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n 'toLocaleString', 'toString', 'valueOf'\n];\n\n\n// TODO(johnlenz): share this function with the goog.object\n/**\n * @param {!Object} target The object to add properties to.\n * @param {!Object} source The object to copy properties from.\n * @private\n */\ngoog.defineClass.applyProperties_ = function(target, source) {\n // TODO(johnlenz): update this to support ES5 getters/setters\n\n var key;\n for (key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n};\n\n/**\n * Returns the parameter.\n * @param {string} s\n * @return {string}\n * @private\n */\ngoog.identity_ = function(s) {\n return s;\n};\n\n\n/**\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\n * The policy just blesses any string as a Trusted Type. It is not visibility\n * restricted because anyone can also call trustedTypes.createPolicy directly.\n * However, the allowed names should be restricted by a HTTP header and the\n * reference to the created policy should be visibility restricted.\n * @param {string} name\n * @return {?TrustedTypePolicy}\n */\ngoog.createTrustedTypesPolicy = function(name) {\n var policy = null;\n var policyFactory = goog.global.trustedTypes;\n if (!policyFactory || !policyFactory.createPolicy) {\n return policy;\n }\n // trustedTypes.createPolicy throws if called with a name that is already\n // registered, even in report-only mode. Until the API changes, catch the\n // error not to break the applications functionally. In such case, the code\n // will fall back to using regular Safe Types.\n // TODO(koto): Remove catching once createPolicy API stops throwing.\n try {\n policy = policyFactory.createPolicy(name, {\n createHTML: goog.identity_,\n createScript: goog.identity_,\n createScriptURL: goog.identity_\n });\n } catch (e) {\n goog.logToConsole_(e.message);\n }\n return policy;\n};\n\n// There's a bug in the compiler where without collapse properties the\n// Closure namespace defines do not guard code correctly. To help reduce code\n// size also check for !COMPILED even though it redundant until this is fixed.\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n\n\n /**\n * Tries to detect whether the current browser is Edge, based on the user\n * agent. This matches only pre-Chromium Edge.\n * @see https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string\n * @return {boolean} True if the current browser is Edge.\n * @private\n */\n goog.isEdge_ = function() {\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n goog.global.navigator.userAgent :\n '';\n var edgeRe = /Edge\\/(\\d+)(\\.\\d)*/i;\n return !!userAgent.match(edgeRe);\n };\n\n\n /**\n * Tries to detect whether is in the context of an HTML document.\n * @return {boolean} True if it looks like HTML document.\n * @private\n */\n goog.inHtmlDocument_ = function() {\n /** @type {!Document} */\n var doc = goog.global.document;\n return doc != null && 'write' in doc; // XULDocument misses write.\n };\n\n\n /**\n * We'd like to check for if the document readyState is 'loading'; however\n * there are bugs on IE 10 and below where the readyState being anything other\n * than 'complete' is not reliable.\n * @return {boolean}\n * @private\n */\n goog.isDocumentLoading_ = function() {\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n // detect those browsers.\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n return doc.attachEvent ? doc.readyState != 'complete' :\n doc.readyState == 'loading';\n };\n\n\n /**\n * Tries to detect the base path of base.js script that bootstraps Closure.\n * @private\n */\n goog.findBasePath_ = function() {\n if (goog.global.CLOSURE_BASE_PATH != undefined &&\n // Anti DOM-clobbering runtime check (b/37736576).\n typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\n return;\n } else if (!goog.inHtmlDocument_()) {\n return;\n }\n /** @type {!Document} */\n var doc = goog.global.document;\n // If we have a currentScript available, use it exclusively.\n var currentScript = doc.currentScript;\n if (currentScript) {\n var scripts = [currentScript];\n } else {\n var scripts = doc.getElementsByTagName('SCRIPT');\n }\n // Search backwards since the current script is in almost all cases the one\n // that has base.js.\n for (var i = scripts.length - 1; i >= 0; --i) {\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n var src = script.src;\n var qmark = src.lastIndexOf('?');\n var l = qmark == -1 ? src.length : qmark;\n if (src.substr(l - 7, 7) == 'base.js') {\n goog.basePath = src.substr(0, l - 7);\n return;\n }\n }\n };\n\n goog.findBasePath_();\n\n /** @struct @constructor @final */\n goog.Transpiler = function() {\n /** @private {?Object<string, boolean>} */\n this.requiresTranspilation_ = null;\n /** @private {string} */\n this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;\n };\n /**\n * Returns a newly created map from language mode string to a boolean\n * indicating whether transpilation should be done for that mode as well as\n * the highest level language that this environment supports.\n *\n * Guaranteed invariant:\n * For any two modes, l1 and l2 where l2 is a newer mode than l1,\n * `map[l1] == true` implies that `map[l2] == true`.\n *\n * Note this method is extracted and used elsewhere, so it cannot rely on\n * anything external (it should easily be able to be transformed into a\n * standalone, top level function).\n *\n * @private\n * @return {{\n * target: string,\n * map: !Object<string, boolean>\n * }}\n */\n goog.Transpiler.prototype.createRequiresTranspilation_ = function() {\n var transpilationTarget = 'es3';\n var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};\n var transpilationRequiredForAllLaterModes = false;\n\n /**\n * Adds an entry to requiresTranspliation for the given language mode.\n *\n * IMPORTANT: Calls must be made in order from oldest to newest language\n * mode.\n * @param {string} modeName\n * @param {function(): boolean} isSupported Returns true if the JS engine\n * supports the given mode.\n */\n function addNewerLanguageTranspilationCheck(modeName, isSupported) {\n if (transpilationRequiredForAllLaterModes) {\n requiresTranspilation[modeName] = true;\n } else if (isSupported()) {\n transpilationTarget = modeName;\n requiresTranspilation[modeName] = false;\n } else {\n requiresTranspilation[modeName] = true;\n transpilationRequiredForAllLaterModes = true;\n }\n }\n\n /**\n * Does the given code evaluate without syntax errors and return a truthy\n * result?\n */\n function /** boolean */ evalCheck(/** string */ code) {\n try {\n return !!eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(code));\n } catch (ignored) {\n return false;\n }\n }\n\n // Identify ES3-only browsers by their incorrect treatment of commas.\n addNewerLanguageTranspilationCheck('es5', function() {\n return evalCheck('[1,].length==1');\n });\n addNewerLanguageTranspilationCheck('es6', function() {\n // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:\n // https://github.com/Microsoft/ChakraCore/issues/1496.\n if (goog.isEdge_()) {\n // The Reflect.construct test below is flaky on Edge. It can sometimes\n // pass or fail on 40 15.15063, so just exit early for Edge and treat\n // it as ES5. Until we're on a more up to date version just always use\n // ES5. See https://github.com/Microsoft/ChakraCore/issues/3217.\n return false;\n }\n // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]\n // (a) default params (specifically shadowing locals),\n // (b) destructuring, (c) block-scoped functions,\n // (d) for-of (const), (e) new.target/Reflect.construct\n var es6fullTest =\n 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +\n 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +\n 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +\n 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +\n '==3}';\n\n return evalCheck('(()=>{\"use strict\";' + es6fullTest + '})()');\n });\n // ** and **= are the only new features in 'es7'\n addNewerLanguageTranspilationCheck('es7', function() {\n return evalCheck('2**3==8');\n });\n // async functions are the only new features in 'es8'\n addNewerLanguageTranspilationCheck('es8', function() {\n return evalCheck('async()=>1,1');\n });\n addNewerLanguageTranspilationCheck('es9', function() {\n return evalCheck('({...rest}={}),1');\n });\n // optional catch binding, unescaped unicode paragraph separator in strings\n addNewerLanguageTranspilationCheck('es_2019', function() {\n return evalCheck('let r;try{r=\"\\u2029\"}catch{};r');\n });\n // optional chaining, nullish coalescing\n // untested/unsupported: bigint, import meta\n addNewerLanguageTranspilationCheck('es_2020', function() {\n return evalCheck('null?.x??1');\n });\n addNewerLanguageTranspilationCheck('es_next', function() {\n return false; // assume it always need to transpile\n });\n return {target: transpilationTarget, map: requiresTranspilation};\n };\n\n\n /**\n * Determines whether the given language needs to be transpiled.\n * @param {string} lang\n * @param {string|undefined} module\n * @return {boolean}\n */\n goog.Transpiler.prototype.needsTranspile = function(lang, module) {\n if (goog.TRANSPILE == 'always') {\n return true;\n } else if (goog.TRANSPILE == 'never') {\n return false;\n } else if (!this.requiresTranspilation_) {\n var obj = this.createRequiresTranspilation_();\n this.requiresTranspilation_ = obj.map;\n this.transpilationTarget_ = this.transpilationTarget_ || obj.target;\n }\n if (lang in this.requiresTranspilation_) {\n if (this.requiresTranspilation_[lang]) {\n return true;\n } else if (\n goog.inHtmlDocument_() && module == 'es6' &&\n !('noModule' in goog.global.document.createElement('script'))) {\n return true;\n } else {\n return false;\n }\n } else {\n throw new Error('Unknown language mode: ' + lang);\n }\n };\n\n\n /**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @return {string} The transpiled code.\n */\n goog.Transpiler.prototype.transpile = function(code, path) {\n // TODO(johnplaisted): We should delete goog.transpile_ and just have this\n // function. But there's some compile error atm where goog.global is being\n // stripped incorrectly without this.\n return goog.transpile_(code, path, this.transpilationTarget_);\n };\n\n\n /** @private @final {!goog.Transpiler} */\n goog.transpiler_ = new goog.Transpiler();\n\n /**\n * Rewrites closing script tags in input to avoid ending an enclosing script\n * tag.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n goog.protectScriptTag_ = function(str) {\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\n };\n\n\n /**\n * A debug loader is responsible for downloading and executing javascript\n * files in an unbundled, uncompiled environment.\n *\n * This can be custimized via the setDependencyFactory method, or by\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\n *\n * @struct @constructor @final @private\n */\n goog.DebugLoader_ = function() {\n /** @private @const {!Object<string, !goog.Dependency>} */\n this.dependencies_ = {};\n /** @private @const {!Object<string, string>} */\n this.idToPath_ = {};\n /** @private @const {!Object<string, boolean>} */\n this.written_ = {};\n /** @private @const {!Array<!goog.Dependency>} */\n this.loadingDeps_ = [];\n /** @private {!Array<!goog.Dependency>} */\n this.depsToLoad_ = [];\n /** @private {boolean} */\n this.paused_ = false;\n /** @private {!goog.DependencyFactory} */\n this.factory_ = new goog.DependencyFactory(goog.transpiler_);\n /** @private @const {!Object<string, !Function>} */\n this.deferredCallbacks_ = {};\n /** @private @const {!Array<string>} */\n this.deferredQueue_ = [];\n };\n\n /**\n * @param {!Array<string>} namespaces\n * @param {function(): undefined} callback Function to call once all the\n * namespaces have loaded.\n */\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\n var cb = callback;\n function resolve() {\n if (cb) {\n goog.global.setTimeout(cb, 0);\n cb = null;\n }\n }\n\n if (!namespaces.length) {\n resolve();\n return;\n }\n\n var deps = [];\n for (var i = 0; i < namespaces.length; i++) {\n var path = this.getPathFromDeps_(namespaces[i]);\n if (!path) {\n throw new Error('Unregonized namespace: ' + namespaces[i]);\n }\n deps.push(this.dependencies_[path]);\n }\n\n var require = goog.require;\n var loaded = 0;\n for (var i = 0; i < namespaces.length; i++) {\n require(namespaces[i]);\n deps[i].onLoad(function() {\n if (++loaded == namespaces.length) {\n resolve();\n }\n });\n }\n };\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\n // Circumvent addDependency, which would try to transpile deps.js if\n // transpile is set to always.\n var relPath = 'deps.js';\n this.depsToLoad_.push(this.factory_.createDependency(\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},\n false));\n this.loadDeps_();\n };\n\n\n /**\n * Notifies the debug loader when a dependency has been requested.\n *\n * @param {string} absPathOrId Path of the dependency or goog id.\n * @param {boolean=} opt_force\n */\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\n var path = this.getPathFromDeps_(absPathOrId);\n if (path &&\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\n var callback = this.deferredCallbacks_[path];\n if (callback) {\n delete this.deferredCallbacks_[path];\n callback();\n }\n }\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\n this.factory_ = factory;\n };\n\n\n /**\n * Travserses the dependency graph and queues the given dependency, and all of\n * its transitive dependencies, for loading and then starts loading if not\n * paused.\n *\n * @param {string} namespace\n * @private\n */\n goog.DebugLoader_.prototype.load_ = function(namespace) {\n if (!this.getPathFromDeps_(namespace)) {\n var errorMessage = 'goog.require could not find: ' + namespace;\n goog.logToConsole_(errorMessage);\n } else {\n var loader = this;\n\n var deps = [];\n\n /** @param {string} namespace */\n var visit = function(namespace) {\n var path = loader.getPathFromDeps_(namespace);\n\n if (!path) {\n throw new Error('Bad dependency path or symbol: ' + namespace);\n }\n\n if (loader.written_[path]) {\n return;\n }\n\n loader.written_[path] = true;\n\n var dep = loader.dependencies_[path];\n for (var i = 0; i < dep.requires.length; i++) {\n if (!goog.isProvided_(dep.requires[i])) {\n visit(dep.requires[i]);\n }\n }\n\n deps.push(dep);\n };\n\n visit(namespace);\n\n var wasLoading = !!this.depsToLoad_.length;\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\n\n if (!this.paused_ && !wasLoading) {\n this.loadDeps_();\n }\n }\n };\n\n\n /**\n * Loads any queued dependencies until they are all loaded or paused.\n *\n * @private\n */\n goog.DebugLoader_.prototype.loadDeps_ = function() {\n var loader = this;\n var paused = this.paused_;\n\n while (this.depsToLoad_.length && !paused) {\n (function() {\n var loadCallDone = false;\n var dep = loader.depsToLoad_.shift();\n\n var loaded = false;\n loader.loading_(dep);\n\n var controller = {\n pause: function() {\n if (loadCallDone) {\n throw new Error('Cannot call pause after the call to load.');\n } else {\n paused = true;\n }\n },\n resume: function() {\n if (loadCallDone) {\n loader.resume_();\n } else {\n // Some dep called pause and then resume in the same load call.\n // Just keep running this same loop.\n paused = false;\n }\n },\n loaded: function() {\n if (loaded) {\n throw new Error('Double call to loaded.');\n }\n\n loaded = true;\n loader.loaded_(dep);\n },\n pending: function() {\n // Defensive copy.\n var pending = [];\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\n pending.push(loader.loadingDeps_[i]);\n }\n return pending;\n },\n /**\n * @param {goog.ModuleType} type\n */\n setModuleState: function(type) {\n goog.moduleLoaderState_ = {\n type: type,\n moduleName: '',\n declareLegacyNamespace: false\n };\n },\n /** @type {function(string, string, string=)} */\n registerEs6ModuleExports: function(\n path, exports, opt_closureNamespace) {\n if (opt_closureNamespace) {\n goog.loadedModules_[opt_closureNamespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: opt_closureNamespace || ''\n };\n }\n },\n /** @type {function(string, ?)} */\n registerGoogModuleExports: function(moduleId, exports) {\n goog.loadedModules_[moduleId] = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: moduleId\n };\n },\n clearModuleState: function() {\n goog.moduleLoaderState_ = null;\n },\n defer: function(callback) {\n if (loadCallDone) {\n throw new Error(\n 'Cannot register with defer after the call to load.');\n }\n loader.defer_(dep, callback);\n },\n areDepsLoaded: function() {\n return loader.areDepsLoaded_(dep.requires);\n }\n };\n\n try {\n dep.load(controller);\n } finally {\n loadCallDone = true;\n }\n })();\n }\n\n if (paused) {\n this.pause_();\n }\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.pause_ = function() {\n this.paused_ = true;\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.resume_ = function() {\n if (this.paused_) {\n this.paused_ = false;\n this.loadDeps_();\n }\n };\n\n\n /**\n * Marks the given dependency as loading (load has been called but it has not\n * yet marked itself as finished). Useful for dependencies that want to know\n * what else is loading. Example: goog.modules cannot eval if there are\n * loading dependencies.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loading_ = function(dep) {\n this.loadingDeps_.push(dep);\n };\n\n\n /**\n * Marks the given dependency as having finished loading and being available\n * for require.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\n for (var i = 0; i < this.loadingDeps_.length; i++) {\n if (this.loadingDeps_[i] == dep) {\n this.loadingDeps_.splice(i, 1);\n break;\n }\n }\n\n for (var i = 0; i < this.deferredQueue_.length; i++) {\n if (this.deferredQueue_[i] == dep.path) {\n this.deferredQueue_.splice(i, 1);\n break;\n }\n }\n\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\n !this.depsToLoad_.length) {\n // Something has asked to load these, but they may not be directly\n // required again later, so load them now that we know we're done loading\n // everything else. e.g. a goog module entry point.\n while (this.deferredQueue_.length) {\n this.requested(this.deferredQueue_.shift(), true);\n }\n }\n\n dep.loaded();\n };\n\n\n /**\n * @param {!Array<string>} pathsOrIds\n * @return {boolean}\n * @private\n */\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\n for (var i = 0; i < pathsOrIds.length; i++) {\n var path = this.getPathFromDeps_(pathsOrIds[i]);\n if (!path ||\n (!(path in this.deferredCallbacks_) &&\n !goog.isProvided_(pathsOrIds[i]))) {\n return false;\n }\n }\n\n return true;\n };\n\n\n /**\n * @param {string} absPathOrId\n * @return {?string}\n * @private\n */\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\n if (absPathOrId in this.idToPath_) {\n return this.idToPath_[absPathOrId];\n } else if (absPathOrId in this.dependencies_) {\n return absPathOrId;\n } else {\n return null;\n }\n };\n\n\n /**\n * @param {!goog.Dependency} dependency\n * @param {!Function} callback\n * @private\n */\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\n this.deferredCallbacks_[dependency.path] = callback;\n this.deferredQueue_.push(dependency.path);\n };\n\n\n /**\n * Interface for goog.Dependency implementations to have some control over\n * loading of dependencies.\n *\n * @record\n */\n goog.LoadController = function() {};\n\n\n /**\n * Tells the controller to halt loading of more dependencies.\n */\n goog.LoadController.prototype.pause = function() {};\n\n\n /**\n * Tells the controller to resume loading of more dependencies if paused.\n */\n goog.LoadController.prototype.resume = function() {};\n\n\n /**\n * Tells the controller that this dependency has finished loading.\n *\n * This causes this to be removed from pending() and any load callbacks to\n * fire.\n */\n goog.LoadController.prototype.loaded = function() {};\n\n\n /**\n * List of dependencies on which load has been called but which have not\n * called loaded on their controller. This includes the current dependency.\n *\n * @return {!Array<!goog.Dependency>}\n */\n goog.LoadController.prototype.pending = function() {};\n\n\n /**\n * Registers an object as an ES6 module's exports so that goog.modules may\n * require it by path.\n *\n * @param {string} path Full path of the module.\n * @param {?} exports\n * @param {string=} opt_closureNamespace Closure namespace to associate with\n * this module.\n */\n goog.LoadController.prototype.registerEs6ModuleExports = function(\n path, exports, opt_closureNamespace) {};\n\n\n /**\n * Sets the current module state.\n *\n * @param {goog.ModuleType} type Type of module.\n */\n goog.LoadController.prototype.setModuleState = function(type) {};\n\n\n /**\n * Clears the current module state.\n */\n goog.LoadController.prototype.clearModuleState = function() {};\n\n\n /**\n * Registers a callback to call once the dependency is actually requested\n * via goog.require + all of the immediate dependencies have been loaded or\n * all other files have been loaded. Allows for lazy loading until\n * require'd without pausing dependency loading, which is needed on old IE.\n *\n * @param {!Function} callback\n */\n goog.LoadController.prototype.defer = function(callback) {};\n\n\n /**\n * @return {boolean}\n */\n goog.LoadController.prototype.areDepsLoaded = function() {};\n\n\n /**\n * Basic super class for all dependencies Closure Library can load.\n *\n * This default implementation is designed to load untranspiled, non-module\n * scripts in a web broswer.\n *\n * For transpiled non-goog.module files {@see goog.TranspiledDependency}.\n * For goog.modules see {@see goog.GoogModuleDependency}.\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n */\n goog.Dependency = function(\n path, relativePath, provides, requires, loadFlags) {\n /** @const */\n this.path = path;\n /** @const */\n this.relativePath = relativePath;\n /** @const */\n this.provides = provides;\n /** @const */\n this.requires = requires;\n /** @const */\n this.loadFlags = loadFlags;\n /** @private {boolean} */\n this.loaded_ = false;\n /** @private {!Array<function()>} */\n this.loadCallbacks_ = [];\n };\n\n\n /**\n * @return {string} The pathname part of this dependency's path if it is a\n * URI.\n */\n goog.Dependency.prototype.getPathName = function() {\n var pathName = this.path;\n var protocolIndex = pathName.indexOf('://');\n if (protocolIndex >= 0) {\n pathName = pathName.substring(protocolIndex + 3);\n var slashIndex = pathName.indexOf('/');\n if (slashIndex >= 0) {\n pathName = pathName.substring(slashIndex + 1);\n }\n }\n return pathName;\n };\n\n\n /**\n * @param {function()} callback Callback to fire as soon as this has loaded.\n * @final\n */\n goog.Dependency.prototype.onLoad = function(callback) {\n if (this.loaded_) {\n callback();\n } else {\n this.loadCallbacks_.push(callback);\n }\n };\n\n\n /**\n * Marks this dependency as loaded and fires any callbacks registered with\n * onLoad.\n * @final\n */\n goog.Dependency.prototype.loaded = function() {\n this.loaded_ = true;\n var callbacks = this.loadCallbacks_;\n this.loadCallbacks_ = [];\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i]();\n }\n };\n\n\n /**\n * Whether or not document.written / appended script tags should be deferred.\n *\n * @private {boolean}\n */\n goog.Dependency.defer_ = false;\n\n\n /**\n * Map of script ready / state change callbacks. Old IE cannot handle putting\n * these properties on goog.global.\n *\n * @private @const {!Object<string, function(?):undefined>}\n */\n goog.Dependency.callbackMap_ = {};\n\n\n /**\n * @param {function(...?):?} callback\n * @return {string}\n * @private\n */\n goog.Dependency.registerCallback_ = function(callback) {\n var key = Math.random().toString(32);\n goog.Dependency.callbackMap_[key] = callback;\n return key;\n };\n\n\n /**\n * @param {string} key\n * @private\n */\n goog.Dependency.unregisterCallback_ = function(key) {\n delete goog.Dependency.callbackMap_[key];\n };\n\n\n /**\n * @param {string} key\n * @param {...?} var_args\n * @private\n * @suppress {unusedPrivateMembers}\n */\n goog.Dependency.callback_ = function(key, var_args) {\n if (key in goog.Dependency.callbackMap_) {\n var callback = goog.Dependency.callbackMap_[key];\n var args = [];\n for (var i = 1; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n callback.apply(undefined, args);\n } else {\n var errorMessage = 'Callback key ' + key +\n ' does not exist (was base.js loaded more than once?).';\n throw Error(errorMessage);\n }\n };\n\n\n /**\n * Starts loading this dependency. This dependency can pause loading if it\n * needs to and resume it later via the controller interface.\n *\n * When this is loaded it should call controller.loaded(). Note that this will\n * end up calling the loaded method of this dependency; there is no need to\n * call it explicitly.\n *\n * @param {!goog.LoadController} controller\n */\n goog.Dependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n if (this.relativePath == 'deps.js') {\n // Some old code is relying on base.js auto loading deps.js failing with\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\n // CLOSURE_NO_DEPS set to true.\n goog.logToConsole_(\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\n 'or setting CLOSURE_NO_DEPS to true.');\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n // If the user tries to require a new symbol after document load,\n // something has gone terribly wrong. Doing a document.write would\n // wipe out the page. This does not apply to the CSP-compliant method\n // of writing script tags.\n if (doc.readyState == 'complete' &&\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\n // Certain test frameworks load base.js multiple times, which tries\n // to write deps.js each time. If that happens, just fail silently.\n // These frameworks wipe the page between each load of base.js, so this\n // is OK.\n var isDeps = /\\bdeps.js$/.test(this.path);\n if (isDeps) {\n controller.loaded();\n return;\n } else {\n throw Error('Cannot write \"' + this.path + '\" after document load');\n }\n }\n\n var nonce = goog.getScriptNonce_();\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n goog.isDocumentLoading_()) {\n var key;\n var callback = function(script) {\n if (script.readyState && script.readyState != 'complete') {\n script.onload = callback;\n return;\n }\n goog.Dependency.unregisterCallback_(key);\n controller.loaded();\n };\n key = goog.Dependency.registerCallback_(callback);\n\n var defer = goog.Dependency.defer_ ? ' defer' : '';\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script src=\"' + this.path + '\"' + nonceAttr + defer +\n ' id=\"script-' + key + '\"><\\/script>';\n\n script += '<script' + nonceAttr + '>';\n\n if (goog.Dependency.defer_) {\n script += 'document.getElementById(\\'script-' + key +\n '\\').onload = function() {\\n' +\n ' goog.Dependency.callback_(\\'' + key + '\\', this);\\n' +\n '};\\n';\n } else {\n script += 'goog.Dependency.callback_(\\'' + key +\n '\\', document.getElementById(\\'script-' + key + '\\'));';\n }\n\n script += '<\\/script>';\n\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = goog.Dependency.defer_;\n scriptEl.async = false;\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n scriptEl.onload = function() {\n scriptEl.onload = null;\n controller.loaded();\n };\n\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\n this.path;\n doc.head.appendChild(scriptEl);\n }\n };\n\n\n /**\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides Should be an empty array.\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\n * modules for interop purposes.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.Dependency}\n */\n goog.Es6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.Es6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.Es6ModuleDependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n controller.pause();\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var dep = this;\n\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\n // difference between this and just waiting for interactive mode and then\n // appending?\n function write(src, contents) {\n var nonceAttr = '';\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n nonceAttr = ' nonce=\"' + nonce + '\"';\n }\n\n if (contents) {\n var script = '<script type=\"module\" crossorigin' + nonceAttr + '>' +\n contents + '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"' +\n nonceAttr + '></' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n }\n\n function append(src, contents) {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = true;\n scriptEl.async = false;\n scriptEl.type = 'module';\n scriptEl.setAttribute('crossorigin', true);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n if (contents) {\n scriptEl.text = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\n contents;\n } else {\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\n src;\n }\n\n doc.head.appendChild(scriptEl);\n }\n\n var create;\n\n if (goog.isDocumentLoading_()) {\n create = write;\n // We can ONLY call document.write if we are guaranteed that any\n // non-module script tags document.written after this are deferred.\n // Small optimization, in theory document.writing is faster.\n goog.Dependency.defer_ = true;\n } else {\n create = append;\n }\n\n // Write 4 separate tags here:\n // 1) Sets the module state at the correct time (just before execution).\n // 2) A src node for this, which just hopefully lets the browser load it a\n // little early (no need to parse #3).\n // 3) Import the module and register it.\n // 4) Clear the module state at the correct time. Guaranteed to run even\n // if there is an error in the module (#3 will not run if there is an\n // error in the module).\n var beforeKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(beforeKey);\n controller.setModuleState(goog.ModuleType.ES6);\n });\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\n\n // TODO(johnplaisted): Does this really speed up anything?\n create(this.path, undefined);\n\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\n goog.Dependency.unregisterCallback_(registerKey);\n controller.registerEs6ModuleExports(\n dep.path, exports, goog.moduleLoaderState_.moduleName);\n });\n create(\n undefined,\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\n registerKey + '\", m)');\n\n var afterKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(afterKey);\n controller.clearModuleState();\n controller.loaded();\n });\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\n };\n\n\n /**\n * Superclass of any dependency that needs to be loaded into memory,\n * transformed, and then eval'd (goog.modules and transpiled files).\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor @abstract\n * @extends {goog.Dependency}\n */\n goog.TransformedDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.TransformedDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private {?string} */\n this.contents_ = null;\n\n /**\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\n * it does then no other ES6 modules will load after).\n *\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\n * bugs on newer ones.\n *\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\n *\n * @private @const {boolean}\n */\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\n !('noModule' in goog.global.document.createElement('script'));\n };\n goog.inherits(goog.TransformedDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.TransformedDependency.prototype.load = function(controller) {\n var dep = this;\n\n function fetch() {\n dep.contents_ = goog.loadFileSync_(dep.path);\n\n if (dep.contents_) {\n dep.contents_ = dep.transform(dep.contents_);\n if (dep.contents_) {\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\n }\n }\n }\n\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n fetch();\n if (this.contents_ &&\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\n this.contents_ = null;\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\n\n if (!this.lazyFetch_) {\n fetch();\n }\n\n function load() {\n if (dep.lazyFetch_) {\n fetch();\n }\n\n if (!dep.contents_) {\n // loadFileSync_ or transform are responsible. Assume they logged an\n // error.\n return;\n }\n\n if (isEs6) {\n controller.setModuleState(goog.ModuleType.ES6);\n }\n\n var namespace;\n\n try {\n var contents = dep.contents_;\n dep.contents_ = null;\n goog.globalEval(goog.CLOSURE_EVAL_PREFILTER_.createScript(contents));\n if (isEs6) {\n namespace = goog.moduleLoaderState_.moduleName;\n }\n } finally {\n if (isEs6) {\n controller.clearModuleState();\n }\n }\n\n if (isEs6) {\n // Due to circular dependencies this may not be available for require\n // right now.\n goog.global['$jscomp']['require']['ensure'](\n [dep.getPathName()], function() {\n controller.registerEs6ModuleExports(\n dep.path,\n goog.global['$jscomp']['require'](dep.getPathName()),\n namespace);\n });\n }\n\n controller.loaded();\n }\n\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\n // events. If we fetched now and then document.write'd the contents the\n // document.write would be an eval and would execute too soon! Instead write\n // a script tag to fetch and eval synchronously at the correct time.\n function fetchInOwnScriptThenLoad() {\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var key = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(key);\n load();\n });\n\n var nonce = goog.getScriptNonce_();\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script' + nonceAttr + '>' +\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\n '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n\n // If one thing is pending it is this.\n var anythingElsePending = controller.pending().length > 1;\n\n // Additionally if we are meant to defer scripts but the page is still\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\n // meant to defer and anything else is pending then defer (those may be\n // scripts that did not need transformation and are just script tags with\n // defer set to true, and we need to evaluate after that deferred script).\n var needsAsyncLoading = goog.Dependency.defer_ &&\n (anythingElsePending || goog.isDocumentLoading_());\n\n if (needsAsyncLoading) {\n // Note that we only defer when we have to rather than 100% of the time.\n // Always defering would work, but then in theory the order of\n // goog.require calls would then matter. We want to enforce that most of\n // the time the order of the require calls does not matter.\n controller.defer(function() {\n load();\n });\n return;\n }\n // TODO(johnplaisted): Externs are missing onreadystatechange for\n // HTMLDocument.\n /** @type {?} */\n var doc = goog.global.document;\n\n var isInternetExplorerOrEdge = goog.inHtmlDocument_() &&\n ('ActiveXObject' in goog.global || goog.isEdge_());\n\n // Don't delay in any version of IE or pre-Chromium Edge. There's a bug\n // around this that will cause out of order script execution. This means\n // that on older IE ES6 modules will load too early (while the document is\n // still loading + the dom is not available). The other option is to load\n // too late (when the document is complete and the onload even will never\n // fire). This seems to be the lesser of two evils as scripts already act\n // like the former.\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n !isInternetExplorerOrEdge) {\n goog.Dependency.defer_ = true;\n // Transpiled ES6 modules still need to load like regular ES6 modules,\n // aka only after the document is interactive.\n controller.pause();\n var oldCallback = doc.onreadystatechange;\n doc.onreadystatechange = function() {\n if (doc.readyState == 'interactive') {\n doc.onreadystatechange = oldCallback;\n load();\n controller.resume();\n }\n if (typeof oldCallback === 'function') {\n oldCallback.apply(undefined, arguments);\n }\n };\n } else {\n // Always eval on old IE.\n if (!goog.inHtmlDocument_() || !goog.isDocumentLoading_()) {\n load();\n } else {\n fetchInOwnScriptThenLoad();\n }\n }\n };\n\n\n /**\n * @param {string} contents\n * @return {string}\n * @abstract\n */\n goog.TransformedDependency.prototype.transform = function(contents) {};\n\n\n /**\n * Any non-goog.module dependency which needs to be transpiled before eval.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.TranspiledDependency = function(\n path, relativePath, provides, requires, loadFlags, transpiler) {\n goog.TranspiledDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @protected @const*/\n this.transpiler = transpiler;\n };\n goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.TranspiledDependency.prototype.transform = function(contents) {\n // Transpile with the pathname so that ES6 modules are domain agnostic.\n return this.transpiler.transpile(contents, this.getPathName());\n };\n\n\n /**\n * An ES6 module dependency that was transpiled to a jscomp module outside\n * of the debug loader, e.g. server side.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.PreTranspiledEs6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.PreTranspiledEs6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\n contents) {\n return contents;\n };\n\n\n /**\n * A goog.module, transpiled or not. Will always perform some minimal\n * transformation even when not transpiled to wrap in a goog.loadModule\n * statement.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @param {boolean} needsTranspile\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.GoogModuleDependency = function(\n path, relativePath, provides, requires, loadFlags, needsTranspile,\n transpiler) {\n goog.GoogModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private @const */\n this.needsTranspile_ = needsTranspile;\n /** @private @const */\n this.transpiler_ = transpiler;\n };\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.GoogModuleDependency.prototype.transform = function(contents) {\n if (this.needsTranspile_) {\n contents = this.transpiler_.transpile(contents, this.getPathName());\n }\n\n if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n return '' +\n 'goog.loadModule(function(exports) {' +\n '\"use strict\";' + contents +\n '\\n' + // terminate any trailing single line comment.\n ';return exports' +\n '});' +\n '\\n//# sourceURL=' + this.path + '\\n';\n } else {\n return '' +\n 'goog.loadModule(' +\n goog.global.JSON.stringify(\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\n ');';\n }\n };\n\n\n /**\n * @param {string} relPath\n * @param {!Array<string>|undefined} provides\n * @param {!Array<string>} requires\n * @param {boolean|!Object<string>=} opt_loadFlags\n * @see goog.addDependency\n */\n goog.DebugLoader_.prototype.addDependency = function(\n relPath, provides, requires, opt_loadFlags) {\n provides = provides || [];\n relPath = relPath.replace(/\\\\/g, '/');\n var path = goog.normalizePath_(goog.basePath + relPath);\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\n }\n var dep = this.factory_.createDependency(\n path, relPath, provides, requires, opt_loadFlags,\n goog.transpiler_.needsTranspile(\n opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));\n this.dependencies_[path] = dep;\n for (var i = 0; i < provides.length; i++) {\n this.idToPath_[provides[i]] = path;\n }\n this.idToPath_[relPath] = path;\n };\n\n\n /**\n * Creates goog.Dependency instances for the debug loader to load.\n *\n * Should be overridden to have the debug loader use custom subclasses of\n * goog.Dependency.\n *\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n */\n goog.DependencyFactory = function(transpiler) {\n /** @protected @const */\n this.transpiler = transpiler;\n };\n\n\n /**\n * @param {string} path Absolute path of the file.\n * @param {string} relativePath Path relative to closure’s base.js.\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\n * @param {!Array<string>} requires Array of required goog.provide/module /\n * relative ES6 module paths.\n * @param {!Object<string, string>} loadFlags\n * @param {boolean} needsTranspile True if the file needs to be transpiled\n * per the goog.Transpiler.\n * @return {!goog.Dependency}\n */\n goog.DependencyFactory.prototype.createDependency = function(\n path, relativePath, provides, requires, loadFlags, needsTranspile) {\n\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\n return new goog.GoogModuleDependency(\n path, relativePath, provides, requires, loadFlags, needsTranspile,\n this.transpiler);\n } else if (needsTranspile) {\n return new goog.TranspiledDependency(\n path, relativePath, provides, requires, loadFlags, this.transpiler);\n } else {\n if (loadFlags['module'] == goog.ModuleType.ES6) {\n if (goog.TRANSPILE == 'never' && goog.ASSUME_ES_MODULES_TRANSPILED) {\n return new goog.PreTranspiledEs6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n return new goog.Es6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n }\n } else {\n return new goog.Dependency(\n path, relativePath, provides, requires, loadFlags);\n }\n }\n };\n\n\n /** @private @const */\n goog.debugLoader_ = new goog.DebugLoader_();\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.loadClosureDeps = function() {\n goog.debugLoader_.loadClosureDeps();\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * Note: if you wish to call this function and provide your own implemnetation\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\n * file and all of its goog.addDependency calls will use the default factory.\n * You can call goog.loadClosureDeps to load the Closure dependency file\n * later, after your factory is injected.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.setDependencyFactory = function(factory) {\n goog.debugLoader_.setDependencyFactory(factory);\n };\n\n\n /**\n * Trusted Types policy for the debug loader.\n * @private @const {?TrustedTypePolicy}\n */\n goog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n null;\n\n if (!goog.global.CLOSURE_NO_DEPS) {\n goog.debugLoader_.loadClosureDeps();\n }\n\n\n /**\n * Bootstraps the given namespaces and calls the callback once they are\n * available either via goog.require. This is a replacement for using\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\n * in an HTML file would guarantee that the require'd namespace was available\n * in the next immediate script tag. With ES6 modules this no longer a\n * guarantee.\n *\n * @param {!Array<string>} namespaces\n * @param {function(): ?} callback Function to call once all the namespaces\n * have loaded. Always called asynchronously.\n */\n goog.bootstrap = function(namespaces, callback) {\n goog.debugLoader_.bootstrap(namespaces, callback);\n };\n}\n\n\nif (!COMPILED) {\n var isChrome87 = false;\n // Cannot run check for Chrome <87 bug in case of strict CSP environments.\n // TODO(user): Remove once Chrome <87 bug is no longer a problem.\n try {\n isChrome87 = eval(goog.global.trustedTypes.emptyScript) !==\n goog.global.trustedTypes.emptyScript;\n } catch (err) {\n }\n\n /**\n * Trusted Types for running dev servers.\n *\n * @private @const\n */\n goog.CLOSURE_EVAL_PREFILTER_ =\n // Detect Chrome <87 bug with TT and eval.\n goog.global.trustedTypes && isChrome87 &&\n goog.createTrustedTypesPolicy('goog#base#devonly#eval') ||\n {createScript: goog.identity_};\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implements the disposable interface.\n */\n\ngoog.provide('goog.Disposable');\n\ngoog.require('goog.disposable.IDisposable');\ngoog.require('goog.dispose');\n/**\n * TODO(user): Remove this require.\n * @suppress {extraRequire}\n */\ngoog.require('goog.disposeAll');\n\n/**\n * Class that provides the basic implementation for disposable objects. If your\n * class holds references or resources that can't be collected by standard GC,\n * it should extend this class or implement the disposable interface (defined\n * in goog.disposable.IDisposable). See description of\n * goog.disposable.IDisposable for examples of cleanup.\n * @constructor\n * @implements {goog.disposable.IDisposable}\n */\ngoog.Disposable = function() {\n 'use strict';\n /**\n * If monitoring the goog.Disposable instances is enabled, stores the creation\n * stack trace of the Disposable instance.\n * @type {string|undefined}\n */\n this.creationStack;\n\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\n this.creationStack = new Error().stack;\n }\n goog.Disposable.instances_[goog.getUid(this)] = this;\n }\n // Support sealing\n this.disposed_ = this.disposed_;\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\n};\n\n\n/**\n * @enum {number} Different monitoring modes for Disposable.\n */\ngoog.Disposable.MonitoringMode = {\n /**\n * No monitoring.\n */\n OFF: 0,\n /**\n * Creating and disposing the goog.Disposable instances is monitored. All\n * disposable objects need to call the `goog.Disposable` base\n * constructor. The PERMANENT mode must be switched on before creating any\n * goog.Disposable instances.\n */\n PERMANENT: 1,\n /**\n * INTERACTIVE mode can be switched on and off on the fly without producing\n * errors. It also doesn't warn if the disposable objects don't call the\n * `goog.Disposable` base constructor.\n */\n INTERACTIVE: 2\n};\n\n\n/**\n * @define {number} The monitoring mode of the goog.Disposable\n * instances. Default is OFF. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.Disposable.MONITORING_MODE =\n goog.define('goog.Disposable.MONITORING_MODE', 0);\n\n\n/**\n * @define {boolean} Whether to attach creation stack to each created disposable\n * instance; This is only relevant for when MonitoringMode != OFF.\n */\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\n\n\n/**\n * Maps the unique ID of every undisposed `goog.Disposable` object to\n * the object itself.\n * @type {!Object<number, !goog.Disposable>}\n * @private\n */\ngoog.Disposable.instances_ = {};\n\n\n/**\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\n * haven't been disposed of.\n */\ngoog.Disposable.getUndisposedObjects = function() {\n 'use strict';\n var ret = [];\n for (var id in goog.Disposable.instances_) {\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\n ret.push(goog.Disposable.instances_[Number(id)]);\n }\n }\n return ret;\n};\n\n\n/**\n * Clears the registry of undisposed objects but doesn't dispose of them.\n */\ngoog.Disposable.clearUndisposedObjects = function() {\n 'use strict';\n goog.Disposable.instances_ = {};\n};\n\n\n/**\n * Whether the object has been disposed of.\n * @type {boolean}\n * @private\n */\ngoog.Disposable.prototype.disposed_ = false;\n\n\n/**\n * Callbacks to invoke when this object is disposed.\n * @type {Array<!Function>}\n * @private\n */\ngoog.Disposable.prototype.onDisposeCallbacks_;\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @override\n */\ngoog.Disposable.prototype.isDisposed = function() {\n 'use strict';\n return this.disposed_;\n};\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @deprecated Use {@link #isDisposed} instead.\n */\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\n\n\n/**\n * Disposes of the object. If the object hasn't already been disposed of, calls\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\n * override {@link #disposeInternal} in order to cleanup references, resources\n * and other disposable objects. Reentrant.\n *\n * @return {void} Nothing.\n * @override\n */\ngoog.Disposable.prototype.dispose = function() {\n 'use strict';\n if (!this.disposed_) {\n // Set disposed_ to true first, in case during the chain of disposal this\n // gets disposed recursively.\n this.disposed_ = true;\n this.disposeInternal();\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n var uid = goog.getUid(this);\n if (goog.Disposable.MONITORING_MODE ==\n goog.Disposable.MonitoringMode.PERMANENT &&\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\n throw new Error(\n this + ' did not call the goog.Disposable base ' +\n 'constructor or was disposed of after a clearUndisposedObjects ' +\n 'call');\n }\n if (goog.Disposable.MONITORING_MODE !=\n goog.Disposable.MonitoringMode.OFF &&\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\n throw new Error(\n this + ' did not empty its onDisposeCallbacks queue. This ' +\n 'probably means it overrode dispose() or disposeInternal() ' +\n 'without calling the superclass\\' method.');\n }\n delete goog.Disposable.instances_[uid];\n }\n }\n};\n\n\n/**\n * Associates a disposable object with this object so that they will be disposed\n * together.\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\n * this object is disposed.\n */\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\n 'use strict';\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\n};\n\n\n/**\n * Invokes a callback function when this object is disposed. Callbacks are\n * invoked in the order in which they were added. If a callback is added to\n * an already disposed Disposable, it will be called immediately.\n * @param {function(this:T):?} callback The callback function.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @template T\n */\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\n 'use strict';\n if (this.disposed_) {\n opt_scope !== undefined ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n opt_scope !== undefined ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Performs appropriate cleanup. See description of goog.disposable.IDisposable\n * for examples. Classes that extend `goog.Disposable` should override this\n * method. Not reentrant. To avoid calling it twice, it must only be called from\n * the subclass' `disposeInternal` method. Everywhere else the public `dispose`\n * method must be used. For example:\n *\n * <pre>\n * mypackage.MyClass = function() {\n * mypackage.MyClass.base(this, 'constructor');\n * // Constructor logic specific to MyClass.\n * ...\n * };\n * goog.inherits(mypackage.MyClass, goog.Disposable);\n *\n * mypackage.MyClass.prototype.disposeInternal = function() {\n * // Dispose logic specific to MyClass.\n * ...\n * // Call superclass's disposeInternal at the end of the subclass's, like\n * // in C++, to avoid hard-to-catch issues.\n * mypackage.MyClass.base(this, 'disposeInternal');\n * };\n * </pre>\n *\n * @protected\n */\ngoog.Disposable.prototype.disposeInternal = function() {\n 'use strict';\n if (this.onDisposeCallbacks_) {\n while (this.onDisposeCallbacks_.length) {\n this.onDisposeCallbacks_.shift()();\n }\n }\n};\n\n\n/**\n * Returns True if we can verify the object is disposed.\n * Calls `isDisposed` on the argument if it supports it. If obj\n * is not an object with an isDisposed() method, return false.\n * @param {*} obj The object to investigate.\n * @return {boolean} True if we can verify the object is disposed.\n */\ngoog.Disposable.isDisposed = function(obj) {\n 'use strict';\n if (obj && typeof obj.isDisposed == 'function') {\n return obj.isDisposed();\n }\n return false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating arrays.\n */\n\n\ngoog.module('goog.array');\ngoog.module.declareLegacyNamespace();\n\nconst asserts = goog.require('goog.asserts');\n\n\n/**\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\n * rely on Array.prototype functions, if available.\n *\n * The Array.prototype functions can be defined by external libraries like\n * Prototype and setting this flag to false forces closure to use its own\n * goog.array implementation.\n *\n * If your javascript can be loaded by a third party site and you are wary about\n * relying on the prototype functions, specify\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\n *\n * Setting goog.TRUSTED_SITE to false will automatically set\n * NATIVE_ARRAY_PROTOTYPES to false.\n */\ngoog.NATIVE_ARRAY_PROTOTYPES =\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\n\n\n/**\n * @define {boolean} If true, JSCompiler will use the native implementation of\n * array functions where appropriate (e.g., `Array#filter`) and remove the\n * unused pure JS implementation.\n */\nconst ASSUME_NATIVE_FUNCTIONS = goog.define(\n 'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);\nexports.ASSUME_NATIVE_FUNCTIONS = ASSUME_NATIVE_FUNCTIONS;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.last}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nfunction peek(array) {\n return array[array.length - 1];\n}\nexports.peek = peek;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.peek}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nexports.last = peek;\n\n// NOTE(arv): Since most of the array functions are generic it allows you to\n// pass an array-like object. Strings have a length and are considered array-\n// like. However, the 'in' operator does not work on strings so we cannot just\n// use the array path even if the browser supports indexing into strings. We\n// therefore end up splitting the string.\n\n\n/**\n * Returns the index of the first element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\n *\n * @param {IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at index 0.\n * @return {number} The index of the first matching array element.\n * @template T\n */\nconst indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n const fromIndex = opt_fromIndex == null ?\n 0 :\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\n opt_fromIndex);\n\n if (typeof arr === 'string') {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.indexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i < arr.length; i++) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.indexOf = indexOf;\n\n\n/**\n * Returns the index of the last element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\n *\n * @param {!IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {?number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at the end of the array.\n * @return {number} The index of the last matching array element.\n * @template T\n */\nconst lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n // Firefox treats undefined and null as 0 in the fromIndex argument which\n // leads it to always return -1\n const fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n let fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n\n if (fromIndex < 0) {\n fromIndex = Math.max(0, arr.length + fromIndex);\n }\n\n if (typeof arr === 'string') {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.lastIndexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i >= 0; i--) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.lastIndexOf = lastIndexOf;\n\n\n/**\n * Calls a function for each element in an array. Skips holes in the array.\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\n *\n * @param {IArrayLike<T>|string} arr Array or array like object over\n * which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function takes 3 arguments (the element, the index and the\n * array). The return value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @template T,S\n */\nconst forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n Array.prototype.forEach.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n };\nexports.forEach = forEach;\n\n\n/**\n * Calls a function for each element in an array, starting from the last\n * element rather than the first.\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function\n * takes 3 arguments (the element, the index and the array). The return\n * value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @template T,S\n */\nfunction forEachRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; --i) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n}\nexports.forEachRight = forEachRight;\n\n\n/**\n * Calls a function for each element in an array, and if the function returns\n * true adds the element to a new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and must\n * return a Boolean. If the return value is true the element is added to the\n * result array. If it is false the element is not included.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {!Array<T>} a new array in which only elements that passed the test\n * are present.\n * @template T,S\n */\nconst filter = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.filter.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = [];\n let resLength = 0;\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n const val = arr2[i]; // in case f mutates arr2\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\n res[resLength++] = val;\n }\n }\n }\n return res;\n };\nexports.filter = filter;\n\n\n/**\n * Calls a function for each element in an array and inserts the result into a\n * new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\n *\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\n * for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return something. The result will be\n * inserted into a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the results from f.\n * @template THIS, VALUE, RESULT\n */\nconst map = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.map.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = new Array(l);\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n return res;\n };\nexports.map = map;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\n * Note that this implementation differs from the native Array.prototype.reduce\n * in that the initial value is assumed to be defined (the MDN docs linked above\n * recommend not omitting this parameter, although it is technically optional).\n *\n * For example:\n * var a = [1, 2, 3, 4];\n * reduce(a, function(r, v, i, arr) {return r + v;}, 0);\n * returns 10\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Result of evaluating f repeatedly across the values of the array.\n * @template T,S,R\n */\nconst reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduce.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEach(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduce = reduce;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result,\n * starting from the last element and working towards the first.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\n *\n * For example:\n * var a = ['a', 'b', 'c'];\n * reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\n * returns 'cba'\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Object returned as a result of evaluating f repeatedly across the\n * values of the array.\n * @template T,S,R\n */\nconst reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n asserts.assert(f != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduceRight.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEachRight(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduceRight = reduceRight;\n\n\n/**\n * Calls f for each element of an array. If any call returns true, some()\n * returns true (without checking the remaining elements). If all calls\n * return false, some() returns false.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} true if any element passes the test.\n * @template T,S\n */\nconst some = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.some.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return true;\n }\n }\n return false;\n };\nexports.some = some;\n\n\n/**\n * Call f for each element of an array. If all calls return true, every()\n * returns true. If any call returns false, every() returns false and\n * does not continue to check the remaining elements.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} false if any element fails the test.\n * @template T,S\n */\nconst every = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.every.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return false;\n }\n }\n return true;\n };\nexports.every = every;\n\n\n/**\n * Counts the array elements that fulfill the predicate, i.e. for which the\n * callback function returns true. Skips holes in the array.\n *\n * @param {!IArrayLike<T>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\n * every element. Takes 3 arguments (the element, the index and the array).\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @return {number} The number of the matching elements.\n * @template T,S\n */\nfunction count(arr, f, opt_obj) {\n let count = 0;\n forEach(arr, function(element, index, arr) {\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\n ++count;\n }\n }, opt_obj);\n return count;\n}\nexports.count = count;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The first array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction find(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.find = find;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the first array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndex(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndex = findIndex;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The last array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction findRight(arr, f, opt_obj) {\n const i = findIndexRight(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.findRight = findRight;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the last array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndexRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; i--) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndexRight = findIndexRight;\n\n\n/**\n * Whether the array contains the given object.\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\n * element.\n * @param {*} obj The object for which to test.\n * @return {boolean} true if obj is present.\n */\nfunction contains(arr, obj) {\n return indexOf(arr, obj) >= 0;\n}\nexports.contains = contains;\n\n\n/**\n * Whether the array is empty.\n * @param {IArrayLike<?>|string} arr The array to test.\n * @return {boolean} true if empty.\n */\nfunction isEmpty(arr) {\n return arr.length == 0;\n}\nexports.isEmpty = isEmpty;\n\n\n/**\n * Clears the array.\n * @param {IArrayLike<?>} arr Array or array like object to clear.\n */\nfunction clear(arr) {\n // For non real arrays we don't have the magic length so we delete the\n // indices.\n if (!Array.isArray(arr)) {\n for (let i = arr.length - 1; i >= 0; i--) {\n delete arr[i];\n }\n }\n arr.length = 0;\n}\nexports.clear = clear;\n\n\n/**\n * Pushes an item into an array, if it's not already in the array.\n * @param {Array<T>} arr Array into which to insert the item.\n * @param {T} obj Value to add.\n * @template T\n */\nfunction insert(arr, obj) {\n if (!contains(arr, obj)) {\n arr.push(obj);\n }\n}\nexports.insert = insert;\n\n\n/**\n * Inserts an object at the given index of the array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {*} obj The object to insert.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertAt(arr, obj, opt_i) {\n splice(arr, opt_i, 0, obj);\n}\nexports.insertAt = insertAt;\n\n\n/**\n * Inserts at the given index of the array, all elements of another array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertArrayAt(arr, elementsToAdd, opt_i) {\n goog.partial(splice, arr, opt_i, 0).apply(null, elementsToAdd);\n}\nexports.insertArrayAt = insertArrayAt;\n\n\n/**\n * Inserts an object into an array before a specified object.\n * @param {Array<T>} arr The array to modify.\n * @param {T} obj The object to insert.\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\n * is omitted or not found, obj is inserted at the end of the array.\n * @template T\n */\nfunction insertBefore(arr, obj, opt_obj2) {\n let i;\n if (arguments.length == 2 || (i = indexOf(arr, opt_obj2)) < 0) {\n arr.push(obj);\n } else {\n insertAt(arr, obj, i);\n }\n}\nexports.insertBefore = insertBefore;\n\n\n/**\n * Removes the first occurrence of a particular value from an array.\n * @param {IArrayLike<T>} arr Array from which to remove\n * value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction remove(arr, obj) {\n const i = indexOf(arr, obj);\n let rv;\n if ((rv = i >= 0)) {\n removeAt(arr, i);\n }\n return rv;\n}\nexports.remove = remove;\n\n\n/**\n * Removes the last occurrence of a particular value from an array.\n * @param {!IArrayLike<T>} arr Array from which to remove value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction removeLast(arr, obj) {\n const i = lastIndexOf(arr, obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeLast = removeLast;\n\n\n/**\n * Removes from an array the element at index i\n * @param {IArrayLike<?>} arr Array or array like object from which to\n * remove value.\n * @param {number} i The index to remove.\n * @return {boolean} True if an element was removed.\n */\nfunction removeAt(arr, i) {\n asserts.assert(arr.length != null);\n\n // use generic form of splice\n // splice returns the removed items and if successful the length of that\n // will be 1\n return Array.prototype.splice.call(arr, i, 1).length == 1;\n}\nexports.removeAt = removeAt;\n\n\n/**\n * Removes the first value that satisfies the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {boolean} True if an element was removed.\n * @template T,S\n */\nfunction removeIf(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeIf = removeIf;\n\n\n/**\n * Removes all values that satisfy the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The number of items removed\n * @template T,S\n */\nfunction removeAllIf(arr, f, opt_obj) {\n let removedCount = 0;\n forEachRight(arr, function(val, index) {\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\n if (removeAt(arr, index)) {\n removedCount++;\n }\n }\n });\n return removedCount;\n}\nexports.removeAllIf = removeAllIf;\n\n\n/**\n * Returns a new array that is the result of joining the arguments. If arrays\n * are passed then their items are added, however, if non-arrays are passed they\n * will be added to the return array as is.\n *\n * Note that ArrayLike objects will be added as is, rather than having their\n * items added.\n *\n * concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\n * concat(0, [1, 2]) -> [0, 1, 2]\n * concat([1, 2], null) -> [1, 2, null]\n *\n * There is bug in all current versions of IE (6, 7 and 8) where arrays created\n * in an iframe become corrupted soon (not immediately) after the iframe is\n * destroyed. This is common if loading data via goog.net.IframeIo, for example.\n * This corruption only affects the concat method which will start throwing\n * Catastrophic Errors (#-2147418113).\n *\n * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.\n *\n * Internally goog.array should use this, so that all methods will continue to\n * work on these broken array objects.\n *\n * @param {...*} var_args Items to concatenate. Arrays will have each item\n * added, while primitives and objects will be added as is.\n * @return {!Array<?>} The new resultant array.\n */\nfunction concat(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.concat = concat;\n\n\n/**\n * Returns a new array that contains the contents of all the arrays passed.\n * @param {...!Array<T>} var_args\n * @return {!Array<T>}\n * @template T\n */\nfunction join(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.join = join;\n\n\n/**\n * Converts an object to an array.\n * @param {IArrayLike<T>|string} object The object to convert to an\n * array.\n * @return {!Array<T>} The object converted into an array. If object has a\n * length property, every property indexed with a non-negative number\n * less than length will be included in the result. If object does not\n * have a length property, an empty array will be returned.\n * @template T\n */\nfunction toArray(object) {\n const length = object.length;\n\n // If length is not a number the following is false. This case is kept for\n // backwards compatibility since there are callers that pass objects that are\n // not array like.\n if (length > 0) {\n const rv = new Array(length);\n for (let i = 0; i < length; i++) {\n rv[i] = object[i];\n }\n return rv;\n }\n return [];\n}\nexports.toArray = toArray;\n\n\n/**\n * Does a shallow copy of an array.\n * @param {IArrayLike<T>|string} arr Array or array-like object to\n * clone.\n * @return {!Array<T>} Clone of the input array.\n * @template T\n */\nconst clone = toArray;\nexports.clone = clone;\n\n\n/**\n * Extends an array with another array, element, or \"array like\" object.\n * This function operates 'in-place', it does not create a new Array.\n *\n * Example:\n * var a = [];\n * extend(a, [0, 1]);\n * a; // [0, 1]\n * extend(a, 2);\n * a; // [0, 1, 2]\n *\n * @param {Array<VALUE>} arr1 The array to modify.\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\n * elements to add to arr1.\n * @template VALUE\n */\nfunction extend(arr1, var_args) {\n for (let i = 1; i < arguments.length; i++) {\n const arr2 = arguments[i];\n if (goog.isArrayLike(arr2)) {\n const len1 = arr1.length || 0;\n const len2 = arr2.length || 0;\n arr1.length = len1 + len2;\n for (let j = 0; j < len2; j++) {\n arr1[len1 + j] = arr2[j];\n }\n } else {\n arr1.push(arr2);\n }\n }\n}\nexports.extend = extend;\n\n\n/**\n * Adds or removes elements from an array. This is a generic version of Array\n * splice. This means that it might work on other objects similar to arrays,\n * such as the arguments object.\n *\n * @param {IArrayLike<T>} arr The array to modify.\n * @param {number|undefined} index The index at which to start changing the\n * array. If not defined, treated as 0.\n * @param {number} howMany How many elements to remove (0 means no removal. A\n * value below 0 is treated as zero and so is any other non number. Numbers\n * are floored).\n * @param {...T} var_args Optional, additional elements to insert into the\n * array.\n * @return {!Array<T>} the removed elements.\n * @template T\n */\nfunction splice(arr, index, howMany, var_args) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.splice.apply(arr, slice(arguments, 1));\n}\nexports.splice = splice;\n\n\n/**\n * Returns a new array from a segment of an array. This is a generic version of\n * Array slice. This means that it might work on other objects similar to\n * arrays, such as the arguments object.\n *\n * @param {IArrayLike<T>|string} arr The array from\n * which to copy a segment.\n * @param {number} start The index of the first element to copy.\n * @param {number=} opt_end The index after the last element to copy.\n * @return {!Array<T>} A new array containing the specified segment of the\n * original array.\n * @template T\n */\nfunction slice(arr, start, opt_end) {\n asserts.assert(arr.length != null);\n\n // passing 1 arg to slice is not the same as passing 2 where the second is\n // null or undefined (in that case the second argument is treated as 0).\n // we could use slice on the arguments object and then use apply instead of\n // testing the length\n if (arguments.length <= 2) {\n return Array.prototype.slice.call(arr, start);\n } else {\n return Array.prototype.slice.call(arr, start, opt_end);\n }\n}\nexports.slice = slice;\n\n\n/**\n * Removes all duplicates from an array (retaining only the first\n * occurrence of each array element). This function modifies the\n * array in place and doesn't change the order of the non-duplicate items.\n *\n * For objects, duplicates are identified as having the same unique ID as\n * defined by {@link goog.getUid}.\n *\n * Alternatively you can specify a custom hash function that returns a unique\n * value for each item in the array it should consider unique.\n *\n * Runtime: N,\n * Worstcase space: 2N (no dupes)\n *\n * @param {IArrayLike<T>} arr The array from which to remove\n * duplicates.\n * @param {Array=} opt_rv An optional array in which to return the results,\n * instead of performing the removal inplace. If specified, the original\n * array will remain unchanged.\n * @param {function(T):string=} opt_hashFn An optional function to use to\n * apply to every item in the array. This function should return a unique\n * value for each item in the array it should consider unique.\n * @template T\n */\nfunction removeDuplicates(arr, opt_rv, opt_hashFn) {\n const returnArray = opt_rv || arr;\n const defaultHashFn = function(item) {\n // Prefix each type with a single character representing the type to\n // prevent conflicting keys (e.g. true and 'true').\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\n (typeof item).charAt(0) + item;\n };\n const hashFn = opt_hashFn || defaultHashFn;\n\n let cursorInsert = 0;\n let cursorRead = 0;\n const seen = {};\n\n while (cursorRead < arr.length) {\n const current = arr[cursorRead++];\n const key = hashFn(current);\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\n seen[key] = true;\n returnArray[cursorInsert++] = current;\n }\n }\n returnArray.length = cursorInsert;\n}\nexports.removeDuplicates = removeDuplicates;\n\n\n/**\n * Searches the specified array for the specified target using the binary\n * search algorithm. If no opt_compareFn is specified, elements are compared\n * using <code>defaultCompare</code>, which compares the elements\n * using the built in < and > operators. This will produce the expected\n * behavior for homogeneous arrays of String(s) and Number(s). The array\n * specified <b>must</b> be sorted in ascending order (as defined by the\n * comparison function). If the array is not sorted, results are undefined.\n * If the array contains multiple instances of the specified target value, the\n * left-most instance will be found.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {TARGET} target The sought value.\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, the target value and an element from your array, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @template TARGET, VALUE\n */\nfunction binarySearch(arr, target, opt_compareFn) {\n return binarySearch_(\n arr, opt_compareFn || defaultCompare, false /* isEvaluator */, target);\n}\nexports.binarySearch = binarySearch;\n\n\n/**\n * Selects an index in the specified array using the binary search algorithm.\n * The evaluator receives an element and determines whether the desired index\n * is before, at, or after it. The evaluator must be consistent (formally,\n * map(map(arr, evaluator, opt_obj), goog.math.sign)\n * must be monotonically non-increasing).\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\n * Evaluator function that receives 3 arguments (the element, the index and\n * the array). Should return a negative number, zero, or a positive number\n * depending on whether the desired index is before, at, or after the\n * element passed to it.\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\n * within evaluator.\n * @return {number} Index of the leftmost element matched by the evaluator, if\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\n * the index of the first element for which the evaluator returns negative,\n * or arr.length if no such element exists. The return value is non-negative\n * iff a match is found.\n * @template THIS, VALUE\n */\nfunction binarySelect(arr, evaluator, opt_obj) {\n return binarySearch_(\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\n opt_obj);\n}\nexports.binarySelect = binarySelect;\n\n\n/**\n * Implementation of a binary search algorithm which knows how to use both\n * comparison functions and evaluators. If an evaluator is provided, will call\n * the evaluator with the given optional data object, conforming to the\n * interface defined in binarySelect. Otherwise, if a comparison function is\n * provided, will call the comparison function against the given data object.\n *\n * This implementation purposefully does not use goog.bind or goog.partial for\n * performance reasons.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<?>} arr The array to be searched.\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\n * Either an evaluator or a comparison function, as defined by binarySearch\n * and binarySelect above.\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\n * comparison function.\n * @param {?=} opt_target If the function is a comparison function, then\n * this is the target to binary search for.\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\n * optional this object for the evaluator.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @private\n */\nfunction binarySearch_(arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\n let left = 0; // inclusive\n let right = arr.length; // exclusive\n let found;\n while (left < right) {\n const middle = left + ((right - left) >>> 1);\n let compareResult;\n if (isEvaluator) {\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\n } else {\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\n // for the type of binarySearch_, which the type system can't express yet.\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\n opt_target, arr[middle]);\n }\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // We are looking for the lowest index so we can't return immediately.\n found = !compareResult;\n }\n }\n // left is the index if found, or the insertion point otherwise.\n // Avoiding bitwise not operator, as that causes a loss in precision for array\n // indexes outside the bounds of a 32-bit signed integer. Array indexes have\n // a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index\n return found ? left : -left - 1;\n}\n\n\n/**\n * Sorts the specified array into ascending order. If no opt_compareFn is\n * specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\n * but will give unpredictable results for heterogeneous lists of strings and\n * numbers with different numbers of digits.\n *\n * This sort is not guaranteed to be stable.\n *\n * Runtime: Same as `Array.prototype.sort`\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\n * function by which the\n * array is to be ordered. Should take 2 arguments to compare, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @template T\n */\nfunction sort(arr, opt_compareFn) {\n // TODO(arv): Update type annotation since null is not accepted.\n arr.sort(opt_compareFn || defaultCompare);\n}\nexports.sort = sort;\n\n\n/**\n * Sorts the specified array into ascending order in a stable way. If no\n * opt_compareFn is specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s).\n *\n * Runtime: Same as `Array.prototype.sort`, plus an additional\n * O(n) overhead of copying the array twice.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\n * by which the array is to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T\n */\nfunction stableSort(arr, opt_compareFn) {\n const compArr = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n compArr[i] = {index: i, value: arr[i]};\n }\n const valueCompareFn = opt_compareFn || defaultCompare;\n function stableCompareFn(obj1, obj2) {\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\n }\n sort(compArr, stableCompareFn);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = compArr[i].value;\n }\n}\nexports.stableSort = stableSort;\n\n\n/**\n * Sort the specified array into ascending order based on item keys\n * returned by the specified key function.\n * If no opt_compareFn is specified, the keys are compared in ascending order\n * using <code>defaultCompare</code>.\n *\n * Runtime: O(S(f(n)), where S is runtime of <code>sort</code>\n * and f(n) is runtime of the key function.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {function(T): K} keyFn Function taking array element and returning\n * a key used for sorting this element.\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\n * by which the keys are to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T,K\n */\nfunction sortByKey(arr, keyFn, opt_compareFn) {\n const keyCompareFn = opt_compareFn || defaultCompare;\n sort(arr, function(a, b) {\n return keyCompareFn(keyFn(a), keyFn(b));\n });\n}\nexports.sortByKey = sortByKey;\n\n\n/**\n * Sorts an array of objects by the specified object key and compare\n * function. If no compare function is provided, the key values are\n * compared in ascending order using <code>defaultCompare</code>.\n * This won't work for keys that get renamed by the compiler. So use\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\n * @param {Array<Object>} arr An array of objects to sort.\n * @param {string} key The object key to sort by.\n * @param {Function=} opt_compareFn The function to use to compare key\n * values.\n */\nfunction sortObjectsByKey(arr, key, opt_compareFn) {\n sortByKey(arr, function(obj) {\n return obj[key];\n }, opt_compareFn);\n}\nexports.sortObjectsByKey = sortObjectsByKey;\n\n\n/**\n * Tells if the array is sorted.\n * @param {!IArrayLike<T>} arr The array.\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\n * array elements.\n * Should take 2 arguments to compare, and return a negative number, zero,\n * or a positive number depending on whether the first argument is less\n * than, equal to, or greater than the second.\n * @param {boolean=} opt_strict If true no equal elements are allowed.\n * @return {boolean} Whether the array is sorted.\n * @template T\n */\nfunction isSorted(arr, opt_compareFn, opt_strict) {\n const compare = opt_compareFn || defaultCompare;\n for (let i = 1; i < arr.length; i++) {\n const compareResult = compare(arr[i - 1], arr[i]);\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\n return false;\n }\n }\n return true;\n}\nexports.isSorted = isSorted;\n\n\n/**\n * Compares two arrays for equality. Two arrays are considered equal if they\n * have the same length and their corresponding elements are equal according to\n * the comparison function.\n *\n * @param {IArrayLike<A>} arr1 The first array to compare.\n * @param {IArrayLike<B>} arr2 The second array to compare.\n * @param {?function(A,B):boolean=} opt_equalsFn Optional comparison function.\n * Should take 2 arguments to compare, and return true if the arguments\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\n * compares the elements using the built-in '===' operator.\n * @return {boolean} Whether the two arrays are equal.\n * @template A\n * @template B\n */\nfunction equals(arr1, arr2, opt_equalsFn) {\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\n arr1.length != arr2.length) {\n return false;\n }\n const l = arr1.length;\n const equalsFn = opt_equalsFn || defaultCompareEquality;\n for (let i = 0; i < l; i++) {\n if (!equalsFn(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nexports.equals = equals;\n\n\n/**\n * 3-way array compare function.\n * @param {!IArrayLike<VALUE>} arr1 The first array to\n * compare.\n * @param {!IArrayLike<VALUE>} arr2 The second array to\n * compare.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is to be ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {number} Negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template VALUE\n */\nfunction compare3(arr1, arr2, opt_compareFn) {\n const compare = opt_compareFn || defaultCompare;\n const l = Math.min(arr1.length, arr2.length);\n for (let i = 0; i < l; i++) {\n const result = compare(arr1[i], arr2[i]);\n if (result != 0) {\n return result;\n }\n }\n return defaultCompare(arr1.length, arr2.length);\n}\nexports.compare3 = compare3;\n\n\n/**\n * Compares its two arguments for order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second,\n * respectively.\n * @template VALUE\n */\nfunction defaultCompare(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\nexports.defaultCompare = defaultCompare;\n\n\n/**\n * Compares its two arguments for inverse order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second,\n * respectively.\n * @template VALUE\n */\nfunction inverseDefaultCompare(a, b) {\n return -defaultCompare(a, b);\n}\nexports.inverseDefaultCompare = inverseDefaultCompare;\n\n\n/**\n * Compares its two arguments for equality, using the built in === operator.\n * @param {*} a The first object to compare.\n * @param {*} b The second object to compare.\n * @return {boolean} True if the two arguments are equal, false otherwise.\n */\nfunction defaultCompareEquality(a, b) {\n return a === b;\n}\nexports.defaultCompareEquality = defaultCompareEquality;\n\n\n/**\n * Inserts a value into a sorted array. The array is not modified if the\n * value is already present.\n * @param {IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to insert.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was inserted.\n * @template VALUE\n */\nfunction binaryInsert(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n if (index < 0) {\n insertAt(array, value, -(index + 1));\n return true;\n }\n return false;\n}\nexports.binaryInsert = binaryInsert;\n\n\n/**\n * Removes a value from a sorted array.\n * @param {!IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to remove.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was removed.\n * @template VALUE\n */\nfunction binaryRemove(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n return (index >= 0) ? removeAt(array, index) : false;\n}\nexports.binaryRemove = binaryRemove;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {IArrayLike<T>} array The array.\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index\n * and the array) and must return a valid object key (a string, number,\n * etc), or undefined, if that object should not be placed in a bucket.\n * @param {S=} opt_obj The object to be used as the value of 'this' within\n * sorter.\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template T,S\n */\nfunction bucket(array, sorter, opt_obj) {\n const buckets = {};\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n const bucket = buckets[key] || (buckets[key] = []);\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucket = bucket;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {!IArrayLike<V>} array The array.\n * @param {function(V, number, !IArrayLike<V>):(K|undefined)} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index,\n * and the array) and must return a value to use as a key, or undefined, if\n * that object should not be placed in a bucket.\n * @return {!Map<K, !Array<V>>} A map, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template K,V\n */\nfunction bucketToMap(array, sorter) {\n const /** !Map<K, !Array<V>> */ buckets = new Map();\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter(value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = [];\n buckets.set(key, bucket);\n }\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucketToMap = bucketToMap;\n\n\n/**\n * Creates a new object built from the provided array and the key-generation\n * function.\n * @param {IArrayLike<T>} arr Array or array like object over\n * which to iterate whose elements will be the values in the new object.\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\n * call for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a string that will be used as the\n * key for the element in the new object. If the function returns the same\n * key for more than one element, the value for that key is\n * implementation-defined.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within keyFunc.\n * @return {!Object<T>} The new object.\n * @template T,S\n */\nfunction toObject(arr, keyFunc, opt_obj) {\n const ret = {};\n forEach(arr, function(element, index) {\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\n element;\n });\n return ret;\n}\nexports.toObject = toObject;\n\n\n/**\n * Creates a new ES6 Map built from the provided array and the key-generation\n * function.\n * @param {!IArrayLike<V>} arr Array or array like object over which to iterate\n * whose elements will be the values in the new object.\n * @param {?function(V, number, ?) : K} keyFunc The function to call for every\n * element. This function takes 3 arguments (the element, the index, and the\n * array) and should return a value that will be used as the key for the\n * element in the new object. If the function returns the same key for more\n * than one element, the value for that key is implementation-defined.\n * @return {!Map<K, V>} The new map.\n * @template K,V\n */\nfunction toMap(arr, keyFunc) {\n const /** !Map<K, V> */ map = new Map();\n\n for (let i = 0; i < arr.length; i++) {\n const element = arr[i];\n map.set(keyFunc(element, i, arr), element);\n }\n\n return map;\n}\nexports.toMap = toMap;\n\n\n/**\n * Creates a range of numbers in an arithmetic progression.\n *\n * Range takes 1, 2, or 3 arguments:\n * <pre>\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\n * range(-2, -5, -1) produces [-2, -3, -4]\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\n * </pre>\n *\n * @param {number} startOrEnd The starting value of the range if an end argument\n * is provided. Otherwise, the start value is 0, and this is the end value.\n * @param {number=} opt_end The optional end value of the range.\n * @param {number=} opt_step The step size between range values. Defaults to 1\n * if opt_step is undefined or 0.\n * @return {!Array<number>} An array of numbers for the requested range. May be\n * an empty array if adding the step would not converge toward the end\n * value.\n */\nfunction range(startOrEnd, opt_end, opt_step) {\n const array = [];\n let start = 0;\n let end = startOrEnd;\n const step = opt_step || 1;\n if (opt_end !== undefined) {\n start = startOrEnd;\n end = opt_end;\n }\n\n if (step * (end - start) < 0) {\n // Sign mismatch: start + step will never reach the end value.\n return [];\n }\n\n if (step > 0) {\n for (let i = start; i < end; i += step) {\n array.push(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n array.push(i);\n }\n }\n return array;\n}\nexports.range = range;\n\n\n/**\n * Returns an array consisting of the given value repeated N times.\n *\n * @param {VALUE} value The value to repeat.\n * @param {number} n The repeat count.\n * @return {!Array<VALUE>} An array with the repeated value.\n * @template VALUE\n */\nfunction repeat(value, n) {\n const array = [];\n for (let i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n}\nexports.repeat = repeat;\n\n\n/**\n * Returns an array consisting of every argument with all arrays\n * expanded in-place recursively.\n *\n * @param {...*} var_args The values to flatten.\n * @return {!Array<?>} An array containing the flattened values.\n */\nfunction flatten(var_args) {\n const CHUNK_SIZE = 8192;\n\n const result = [];\n for (let i = 0; i < arguments.length; i++) {\n const element = arguments[i];\n if (Array.isArray(element)) {\n for (let c = 0; c < element.length; c += CHUNK_SIZE) {\n const chunk = slice(element, c, c + CHUNK_SIZE);\n const recurseResult = flatten.apply(null, chunk);\n for (let r = 0; r < recurseResult.length; r++) {\n result.push(recurseResult[r]);\n }\n }\n } else {\n result.push(element);\n }\n }\n return result;\n}\nexports.flatten = flatten;\n\n\n/**\n * Rotates an array in-place. After calling this method, the element at\n * index i will be the element previously at index (i - n) %\n * array.length, for all values of i between 0 and array.length - 1,\n * inclusive.\n *\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\n *\n * @param {!Array<T>} array The array to rotate.\n * @param {number} n The amount to rotate.\n * @return {!Array<T>} The array.\n * @template T\n */\nfunction rotate(array, n) {\n asserts.assert(array.length != null);\n\n if (array.length) {\n n %= array.length;\n if (n > 0) {\n Array.prototype.unshift.apply(array, array.splice(-n, n));\n } else if (n < 0) {\n Array.prototype.push.apply(array, array.splice(0, -n));\n }\n }\n return array;\n}\nexports.rotate = rotate;\n\n\n/**\n * Moves one item of an array to a new position keeping the order of the rest\n * of the items. Example use case: keeping a list of JavaScript objects\n * synchronized with the corresponding list of DOM elements after one of the\n * elements has been dragged to a new position.\n * @param {!IArrayLike<?>} arr The array to modify.\n * @param {number} fromIndex Index of the item to move between 0 and\n * `arr.length - 1`.\n * @param {number} toIndex Target index between 0 and `arr.length - 1`.\n */\nfunction moveItem(arr, fromIndex, toIndex) {\n asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\n asserts.assert(toIndex >= 0 && toIndex < arr.length);\n // Remove 1 item at fromIndex.\n const removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\n // Insert the removed item at toIndex.\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\n // significantly slower than splice.\n}\nexports.moveItem = moveItem;\n\n\n/**\n * Creates a new array for which the element at position i is an array of the\n * ith element of the provided arrays. The returned array will only be as long\n * as the shortest array provided; additional values are ignored. For example,\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\n *\n * This is similar to the zip() function in Python. See {@link\n * http://docs.python.org/library/functions.html#zip}\n *\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\n * @return {!Array<!Array<?>>} A new array of arrays created from\n * provided arrays.\n */\nfunction zip(var_args) {\n if (!arguments.length) {\n return [];\n }\n const result = [];\n let minLen = arguments[0].length;\n for (let i = 1; i < arguments.length; i++) {\n if (arguments[i].length < minLen) {\n minLen = arguments[i].length;\n }\n }\n for (let i = 0; i < minLen; i++) {\n const value = [];\n for (let j = 0; j < arguments.length; j++) {\n value.push(arguments[j][i]);\n }\n result.push(value);\n }\n return result;\n}\nexports.zip = zip;\n\n\n/**\n * Shuffles the values in the specified array using the Fisher-Yates in-place\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\n * and so resets the state of that random number generator. Similarly, may reset\n * the state of any other specified random number generator.\n *\n * Runtime: O(n)\n *\n * @param {!Array<?>} arr The array to be shuffled.\n * @param {function():number=} opt_randFn Optional random function to use for\n * shuffling.\n * Takes no arguments, and returns a random number on the interval [0, 1).\n * Defaults to Math.random() using JavaScript's built-in Math library.\n */\nfunction shuffle(arr, opt_randFn) {\n const randFn = opt_randFn || Math.random;\n\n for (let i = arr.length - 1; i > 0; i--) {\n // Choose a random array index in [0, i] (inclusive with i).\n const j = Math.floor(randFn() * (i + 1));\n\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n}\nexports.shuffle = shuffle;\n\n\n/**\n * Returns a new array of elements from arr, based on the indexes of elements\n * provided by index_arr. For example, the result of index copying\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\n *\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\n * @template T\n */\nfunction copyByIndex(arr, index_arr) {\n const result = [];\n forEach(index_arr, function(index) {\n result.push(arr[index]);\n });\n return result;\n}\nexports.copyByIndex = copyByIndex;\n\n\n/**\n * Maps each element of the input array into zero or more elements of the output\n * array.\n *\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\n * to call for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return an array. The result will be\n * used to extend a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\n * returned from f.\n * @template THIS, VALUE, RESULT\n */\nfunction concatMap(arr, f, opt_obj) {\n return concat.apply([], map(arr, f, opt_obj));\n}\nexports.concatMap = concatMap;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A base class for event objects.\n */\n\n\ngoog.provide('goog.events.Event');\n\n/**\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\n * goog.Disposable here to not break projects which assume this dependency.\n * @suppress {extraRequire}\n */\ngoog.require('goog.Disposable');\ngoog.require('goog.events.EventId');\n\n\n/**\n * A base class for event objects, so that they can support preventDefault and\n * stopPropagation.\n *\n * @param {string|!goog.events.EventId} type Event Type.\n * @param {Object=} opt_target Reference to the object that is the target of\n * this event. It has to implement the `EventTarget` interface\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\n * @constructor\n */\ngoog.events.Event = function(type, opt_target) {\n 'use strict';\n /**\n * Event type.\n * @type {string}\n */\n this.type = type instanceof goog.events.EventId ? String(type) : type;\n\n /**\n * TODO(tbreisacher): The type should probably be\n * EventTarget|goog.events.EventTarget.\n *\n * Target of the event.\n * @type {Object|undefined}\n */\n this.target = opt_target;\n\n /**\n * Object that had the listener attached.\n * @type {Object|undefined}\n */\n this.currentTarget = this.target;\n\n /**\n * Whether to cancel the event in internal capture/bubble processing for IE.\n * @type {boolean}\n * @private\n */\n this.propagationStopped_ = false;\n\n /**\n * Whether the default action has been prevented.\n * This is a property to match the W3C specification at\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\n * #events-event-type-defaultPrevented}.\n * Must be treated as read-only outside the class.\n * @type {boolean}\n */\n this.defaultPrevented = false;\n};\n\n/**\n * @return {boolean} true iff internal propagation has been stopped.\n */\ngoog.events.Event.prototype.hasPropagationStopped = function() {\n 'use strict';\n return this.propagationStopped_;\n};\n\n/**\n * Stops event propagation.\n * @return {void}\n */\ngoog.events.Event.prototype.stopPropagation = function() {\n 'use strict';\n this.propagationStopped_ = true;\n};\n\n\n/**\n * Prevents the default action, for example a link redirecting to a url.\n * @return {void}\n */\ngoog.events.Event.prototype.preventDefault = function() {\n 'use strict';\n this.defaultPrevented = true;\n};\n\n\n/**\n * Stops the propagation of the event. It is equivalent to\n * `e.stopPropagation()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.stopPropagation = function(e) {\n 'use strict';\n e.stopPropagation();\n};\n\n\n/**\n * Prevents the default action. It is equivalent to\n * `e.preventDefault()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.preventDefault = function(e) {\n 'use strict';\n e.preventDefault();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the events package.\n */\n\ngoog.module('goog.events.BrowserFeature');\ngoog.module.declareLegacyNamespace();\n\n\n/**\n * Tricks Closure Compiler into believing that a function is pure. The compiler\n * assumes that any `valueOf` function is pure, without analyzing its contents.\n *\n * @param {function(): T} fn\n * @return {T}\n * @template T\n */\nconst purify = (fn) => {\n return ({valueOf: fn}).valueOf();\n};\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\nexports = {\n /**\n * Whether touch is enabled in the browser.\n */\n TOUCH_ENABLED:\n ('ontouchstart' in goog.global ||\n !!(goog.global['document'] && document.documentElement &&\n 'ontouchstart' in document.documentElement) ||\n // IE10 uses non-standard touch events, so it has a different check.\n !!(goog.global['navigator'] &&\n (goog.global['navigator']['maxTouchPoints'] ||\n goog.global['navigator']['msMaxTouchPoints']))),\n\n /**\n * Whether addEventListener supports W3C standard pointer events.\n * http://www.w3.org/TR/pointerevents/\n */\n POINTER_EVENTS: ('PointerEvent' in goog.global),\n\n /**\n * Whether addEventListener supports MSPointer events (only used in IE10).\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\n */\n MSPOINTER_EVENTS:\n ('MSPointerEvent' in goog.global &&\n !!(goog.global['navigator'] &&\n goog.global['navigator']['msPointerEnabled'])),\n\n /**\n * Whether addEventListener supports {passive: true}.\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\n */\n PASSIVE_EVENTS: purify(function() {\n // If we're in a web worker or other custom environment, we can't tell.\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\n return false;\n }\n\n var passive = false;\n var options = Object.defineProperty({}, 'passive', {\n get: function() {\n passive = true;\n }\n });\n try {\n goog.global.addEventListener('test', goog.nullFunction, options);\n goog.global.removeEventListener('test', goog.nullFunction, options);\n } catch (e) {\n }\n\n return passive;\n })\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview String functions called from Closure packages that couldn't\n * depend on each other. Outside Closure, use goog.string function which\n * delegate to these.\n */\n\n\ngoog.provide('goog.string.internal');\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n * @see goog.string.startsWith\n */\ngoog.string.internal.startsWith = function(str, prefix) {\n 'use strict';\n return str.lastIndexOf(prefix, 0) == 0;\n};\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n * @see goog.string.endsWith\n */\ngoog.string.internal.endsWith = function(str, suffix) {\n 'use strict';\n const l = str.length - suffix.length;\n return l >= 0 && str.indexOf(suffix, l) == l;\n};\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveStartsWith\n */\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\n 'use strict';\n return goog.string.internal.caseInsensitiveCompare(\n prefix, str.substr(0, prefix.length)) == 0;\n};\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveEndsWith\n */\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n suffix, str.substr(str.length - suffix.length, suffix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n * @see goog.string.caseInsensitiveEquals\n */\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\n 'use strict';\n return str1.toLowerCase() == str2.toLowerCase();\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @see goog.string.isEmptyOrWhitespace\n */\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\n 'use strict';\n // testing length == 0 first is actually slower in all browsers (about the\n // same in Opera).\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return /^[\\s\\xa0]*$/.test(str);\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.internal.trim =\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\n 'use strict';\n return str.trim();\n } : function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\n // character class (as required by section 7.2 of the ECMAScript spec),\n // we explicitly include it in the regexp to enforce consistent\n // cross-browser behavior.\n // NOTE: We don't use String#replace because it might have side effects\n // causing this function to not compile to 0 bytes.\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\n };\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n * @see goog.string.caseInsensitiveCompare\n */\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\n 'use strict';\n const test1 = String(str1).toLowerCase();\n const test2 = String(str2).toLowerCase();\n\n if (test1 < test2) {\n return -1;\n } else if (test1 == test2) {\n return 0;\n } else {\n return 1;\n }\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n * @see goog.string.newLineToBr\n */\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\n};\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars\n * @return {string} An escaped copy of `str`.\n * @see goog.string.htmlEscape\n */\ngoog.string.internal.htmlEscape = function(\n str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n if (opt_isLikelyToContainHtmlChars) {\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;')\n .replace(goog.string.internal.LT_RE_, '&lt;')\n .replace(goog.string.internal.GT_RE_, '&gt;')\n .replace(goog.string.internal.QUOT_RE_, '&quot;')\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;')\n .replace(goog.string.internal.NULL_RE_, '&#0;');\n return str;\n\n } else {\n // quick test helps in the case when there are no chars to replace, in\n // worst case this makes barely a difference to the time taken\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\n\n // str.indexOf is faster than regex.test in this case\n if (str.indexOf('&') != -1) {\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;');\n }\n if (str.indexOf('<') != -1) {\n str = str.replace(goog.string.internal.LT_RE_, '&lt;');\n }\n if (str.indexOf('>') != -1) {\n str = str.replace(goog.string.internal.GT_RE_, '&gt;');\n }\n if (str.indexOf('\"') != -1) {\n str = str.replace(goog.string.internal.QUOT_RE_, '&quot;');\n }\n if (str.indexOf('\\'') != -1) {\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;');\n }\n if (str.indexOf('\\x00') != -1) {\n str = str.replace(goog.string.internal.NULL_RE_, '&#0;');\n }\n return str;\n }\n};\n\n\n/**\n * Regular expression that matches an ampersand, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.AMP_RE_ = /&/g;\n\n\n/**\n * Regular expression that matches a less than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.LT_RE_ = /</g;\n\n\n/**\n * Regular expression that matches a greater than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.GT_RE_ = />/g;\n\n\n/**\n * Regular expression that matches a double quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.QUOT_RE_ = /\"/g;\n\n\n/**\n * Regular expression that matches a single quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\n\n\n/**\n * Regular expression that matches null character, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.NULL_RE_ = /\\x00/g;\n\n\n/**\n * Regular expression that matches any character that needs to be escaped.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n * @see goog.string.whitespaceEscape\n */\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.internal.newLineToBr(\n str.replace(/ /g, ' &#160;'), opt_xml);\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.contains\n */\ngoog.string.internal.contains = function(str, subString) {\n 'use strict';\n return str.indexOf(subString) != -1;\n};\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.caseInsensitiveContains\n */\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\n 'use strict';\n return goog.string.internal.contains(\n str.toLowerCase(), subString.toLowerCase());\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n * @see goog.string.compareVersions\n */\ngoog.string.internal.compareVersions = function(version1, version2) {\n 'use strict';\n let order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n const v1Subs = goog.string.internal.trim(String(version1)).split('.');\n const v2Subs = goog.string.internal.trim(String(version2)).split('.');\n const subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (let subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n let v1Sub = v1Subs[subIdx] || '';\n let v2Sub = v2Subs[subIdx] || '';\n\n do {\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\n // Two different RegExp objects are use to make it clear the code\n // is side-effect free\n const v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n const v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\n // Break if there are no more matches.\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\n break;\n }\n\n // Parse the numeric part of the subversion. A missing number is\n // equivalent to 0.\n const v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n const v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\n\n // Compare the subversion components. The number has the highest\n // precedence. Next, if the numbers are equal, a subversion without any\n // qualifier is always higher than a subversion with any qualifier. Next,\n // the qualifiers are compared as strings.\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\n goog.string.internal.compareElements_(\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\n // Stop as soon as an inequality is discovered.\n\n v1Sub = v1Comp[3];\n v2Sub = v2Comp[3];\n } while (order == 0);\n }\n\n return order;\n};\n\n\n/**\n * Compares elements of a version number.\n *\n * @param {string|number|boolean} left An element from a version number.\n * @param {string|number|boolean} right An element from a version number.\n *\n * @return {number} 1 if `left` is higher.\n * 0 if arguments are equal.\n * -1 if `right` is higher.\n * @private\n */\ngoog.string.internal.compareElements_ = function(left, right) {\n 'use strict';\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n }\n return 0;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\n * should not be used outside of goog.labs.userAgent.*.\n *\n */\n\ngoog.module('goog.labs.userAgent.util');\ngoog.module.declareLegacyNamespace();\n\nconst {USE_CLIENT_HINTS} = goog.require('goog.labs.userAgent');\nconst {caseInsensitiveContains, contains} = goog.require('goog.string.internal');\n\n/**\n * @const {boolean} If true, use navigator.userAgentData without check.\n * TODO(user): FEATURESET_YEAR >= 2023 if it supports mobile and all the\n * brands we need. See https://caniuse.com/mdn-api_navigator_useragentdata.\n */\nconst ASSUME_CLIENT_HINTS_SUPPORT = false;\n\n/**\n * Gets the native userAgent string from navigator if it exists.\n * If navigator or navigator.userAgent string is missing, returns an empty\n * string.\n * @return {string}\n */\nfunction getNativeUserAgentString() {\n const navigator = getNavigator();\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n}\n\n/**\n * Gets the native userAgentData object from navigator if it exists.\n * If navigator.userAgentData object is missing or USE_CLIENT_HINTS is set to\n * false, returns null.\n * @return {?NavigatorUAData}\n */\nfunction getNativeUserAgentData() {\n if (!USE_CLIENT_HINTS) {\n return null;\n }\n const navigator = getNavigator();\n // TODO(user): Use navigator?.userAgent ?? null once it's supported.\n if (navigator) {\n return navigator.userAgentData || null;\n }\n return null;\n}\n\n/**\n * Getter for the native navigator.\n * @return {!Navigator}\n */\nfunction getNavigator() {\n return goog.global.navigator;\n}\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgent but use a specified value for detection instead.\n * @type {?string}\n */\nlet userAgentInternal = null;\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgentData but use a specified value for detection instead.\n * @type {?NavigatorUAData}\n */\nlet userAgentDataInternal = getNativeUserAgentData();\n\n/**\n * Override the user agent string with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to use the native browser object instead.\n * @param {?string=} userAgent The userAgent override.\n * @return {void}\n */\nfunction setUserAgent(userAgent = undefined) {\n userAgentInternal =\n typeof userAgent === 'string' ? userAgent : getNativeUserAgentString();\n}\n\n/** @return {string} The user agent string. */\nfunction getUserAgent() {\n return userAgentInternal == null ? getNativeUserAgentString() :\n userAgentInternal;\n}\n\n/**\n * Override the user agent data object with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to specify the absence of userAgentData. Note that this behavior\n * is different from setUserAgent.\n * @param {?NavigatorUAData} userAgentData The userAgentData override.\n */\nfunction setUserAgentData(userAgentData) {\n userAgentDataInternal = userAgentData;\n}\n\n/**\n * If the user agent data object was overridden using setUserAgentData,\n * reset it so that it uses the native browser object instead, if it exists.\n */\nfunction resetUserAgentData() {\n userAgentDataInternal = getNativeUserAgentData();\n}\n\n/** @return {?NavigatorUAData} Navigator.userAgentData if exist */\nfunction getUserAgentData() {\n return userAgentDataInternal;\n}\n\n/**\n * Checks if any string in userAgentData.brands matches str.\n * Returns false if userAgentData is not supported.\n * @param {string} str\n * @return {boolean} Whether any brand string from userAgentData contains the\n * given string.\n */\nfunction matchUserAgentDataBrand(str) {\n const data = getUserAgentData();\n if (!data) return false;\n return data.brands.some(({brand}) => brand && contains(brand, str));\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string.\n */\nfunction matchUserAgent(str) {\n const userAgent = getUserAgent();\n return contains(userAgent, str);\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string, ignoring\n * case.\n */\nfunction matchUserAgentIgnoreCase(str) {\n const userAgent = getUserAgent();\n return caseInsensitiveContains(userAgent, str);\n}\n\n/**\n * Parses the user agent into tuples for each section.\n * @param {string} userAgent\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents of\n * the parenthetical.\n */\nfunction extractVersionTuples(userAgent) {\n // Matches each section of a user agent string.\n // Example UA:\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\n\n const versionRegExp = new RegExp(\n // Key. Note that a key may have a space.\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\n '([A-Z][\\\\w ]+)' +\n\n '/' + // slash\n '([^\\\\s]+)' + // version (i.e. '5.0b')\n '\\\\s*' + // whitespace\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\n 'g');\n\n const data = [];\n let match;\n\n // Iterate and collect the version tuples. Each iteration will be the\n // next regex match.\n while (match = versionRegExp.exec(userAgent)) {\n data.push([\n match[1], // key\n match[2], // value\n // || undefined as this is not undefined in IE7 and IE8\n match[3] || undefined // info\n ]);\n }\n\n return data;\n}\n\nexports = {\n ASSUME_CLIENT_HINTS_SUPPORT,\n extractVersionTuples,\n getNativeUserAgentString,\n getUserAgent,\n getUserAgentData,\n matchUserAgent,\n matchUserAgentDataBrand,\n matchUserAgentIgnoreCase,\n resetUserAgentData,\n setUserAgent,\n setUserAgentData,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n 'use strict';\n return object;\n};\n\n/**\n * Syntax for renaming property strings.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an need to access a property as a string, but want\n * to also have the property renamed by the compiler. In contrast to\n * goog.reflect.object, this method takes an instance of an object.\n *\n * Properties must be simple names (not qualified names).\n *\n * @param {string} prop Name of the property\n * @param {!Object} object Instance of the object whose type will be used\n * for renaming\n * @return {string} The renamed property.\n */\ngoog.reflect.objectProperty = function(prop, object) {\n 'use strict';\n return prop;\n};\n\n/**\n * To assert to the compiler that an operation is needed when it would\n * otherwise be stripped. For example:\n * <code>\n * // Force a layout\n * goog.reflect.sinkValue(dialog.offsetHeight);\n * </code>\n * @param {T} x\n * @return {T}\n * @template T\n */\ngoog.reflect.sinkValue = function(x) {\n 'use strict';\n goog.reflect.sinkValue[' '](x);\n return x;\n};\n\n\n/**\n * The compiler should optimize this function away iff no one ever uses\n * goog.reflect.sinkValue.\n */\ngoog.reflect.sinkValue[' '] = goog.nullFunction;\n\n\n/**\n * Check if a property can be accessed without throwing an exception.\n * @param {Object} obj The owner of the property.\n * @param {string} prop The property name.\n * @return {boolean} Whether the property is accessible. Will also return true\n * if obj is null.\n */\ngoog.reflect.canAccessProperty = function(obj, prop) {\n 'use strict';\n try {\n goog.reflect.sinkValue(obj[prop]);\n return true;\n } catch (e) {\n }\n return false;\n};\n\n\n/**\n * Retrieves a value from a cache given a key. The compiler provides special\n * consideration for this call such that it is generally considered side-effect\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n * then the entire call is considered to have side-effects.\n *\n * Conventionally storing the value on the cache would be considered a\n * side-effect and preclude unused calls from being pruned, ie. even if\n * the value was never used, it would still always be stored in the cache.\n *\n * Providing a side-effect free `valueFn` and `opt_keyFn`\n * allows unused calls to `goog.reflect.cache` to be pruned.\n *\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n * @param {?} key The key to lookup in the cache. If it is not string or number\n * then a `opt_keyFn` should be provided. The key is also used as the\n * parameter to the `valueFn`.\n * @param {function(?):V} valueFn The value provider to use to calculate the\n * value to store in the cache. This function should be side-effect free\n * to take advantage of the optimization.\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n * map key. This should be used if the given key is not a string or number.\n * If not provided then the given key is used. This function should be\n * side-effect free to take advantage of the optimization.\n * @return {V} The cached or calculated value.\n * @template K\n * @template V\n */\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\n 'use strict';\n const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n return cacheObj[storedKey];\n }\n\n return (cacheObj[storedKey] = valueFn(key));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Rendering engine detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For information on the browser brand (such as Safari versus Chrome), see\n * goog.userAgent.product.\n * @see ../demos/useragent.html\n */\n\ngoog.provide('goog.userAgent');\n\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.reflect');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is IE.\n */\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is EDGE,\n * referring to EdgeHTML based Edge.\n */\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\n */\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\n */\ngoog.userAgent.ASSUME_WEBKIT =\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is a\n * mobile device running WebKit e.g. iPhone or Android.\n */\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is OPERA,\n * referring to Presto-based Opera.\n */\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\n\n\n/**\n * @define {boolean} Whether the\n * `goog.userAgent.isVersionOrHigher`\n * function will return true for any version.\n */\ngoog.userAgent.ASSUME_ANY_VERSION =\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\n\n\n/**\n * Whether we know the browser engine at compile-time.\n * @type {boolean}\n * @private\n */\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\n goog.userAgent.ASSUME_OPERA;\n\n\n/**\n * Returns the userAgent string for the current browser.\n *\n * @return {string} The userAgent string.\n */\ngoog.userAgent.getUserAgentString = function() {\n 'use strict';\n return goog.labs.userAgent.util.getUserAgent();\n};\n\n\n/**\n * @return {?Navigator} The native navigator object.\n */\ngoog.userAgent.getNavigatorTyped = function() {\n 'use strict';\n // Need a local navigator reference instead of using the global one,\n // to avoid the rare case where they reference different objects.\n // (in a WorkerPool, for example).\n return goog.global['navigator'] || null;\n};\n\n\n/**\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\n * @return {?Object} The native navigator object.\n */\ngoog.userAgent.getNavigator = function() {\n 'use strict';\n return goog.userAgent.getNavigatorTyped();\n};\n\n\n/**\n * Whether the user agent is Presto-based Opera.\n * @type {boolean}\n */\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_OPERA :\n goog.labs.userAgent.browser.isOpera();\n\n\n/**\n * Whether the user agent is Internet Explorer.\n * @type {boolean}\n */\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_IE :\n goog.labs.userAgent.browser.isIE();\n\n\n/**\n * Whether the user agent is Microsoft Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_EDGE :\n goog.labs.userAgent.engine.isEdge();\n\n\n/**\n * Whether the user agent is MS Internet Explorer or MS Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\n\n\n/**\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\n * Mozilla, Firefox, and others.\n * @type {boolean}\n */\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_GECKO :\n goog.labs.userAgent.engine.isGecko();\n\n\n/**\n * Whether the user agent is WebKit. WebKit is the rendering engine that\n * Safari, Edge Chromium, Opera Chromium, Android and others use.\n * @type {boolean}\n */\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\n goog.labs.userAgent.engine.isWebKit();\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * This is a separate function so that the logic can be tested.\n *\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\n *\n * @return {boolean} Whether the user agent is running on a mobile device.\n * @private\n */\ngoog.userAgent.isMobile_ = function() {\n 'use strict';\n return goog.userAgent.WEBKIT &&\n goog.labs.userAgent.util.matchUserAgent('Mobile');\n};\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\n * is promoted as the gecko/webkit logic is likely inaccurate.\n *\n * @type {boolean}\n */\ngoog.userAgent.MOBILE =\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\n\n\n/**\n * Used while transitioning code to use WEBKIT instead.\n * @type {boolean}\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\n * TODO(nicksantos): Delete this from goog.userAgent.\n */\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\n\n\n/**\n * @return {string} the platform (operating system) the user agent is running\n * on. Default to empty string because navigator.platform may not be defined\n * (on Rhino, for example).\n * @private\n */\ngoog.userAgent.determinePlatform_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return navigator && navigator.platform || '';\n};\n\n\n/**\n * The platform (operating system) the user agent is running on. Default to\n * empty string because navigator.platform may not be defined (on Rhino, for\n * example).\n * @type {string}\n */\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Macintosh operating\n * system.\n */\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Windows operating\n * system.\n */\ngoog.userAgent.ASSUME_WINDOWS =\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Linux operating\n * system.\n */\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a X11 windowing\n * system.\n */\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on Android.\n */\ngoog.userAgent.ASSUME_ANDROID =\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPhone.\n */\ngoog.userAgent.ASSUME_IPHONE =\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPad.\n */\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPod.\n */\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on KaiOS.\n */\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\n\n\n/**\n * @type {boolean}\n * @private\n */\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD;\n\n\n/**\n * Whether the user agent is running on a Macintosh operating system.\n * @type {boolean}\n */\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_MAC :\n goog.labs.userAgent.platform.isMacintosh();\n\n\n/**\n * Whether the user agent is running on a Windows operating system.\n * @type {boolean}\n */\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_WINDOWS :\n goog.labs.userAgent.platform.isWindows();\n\n\n/**\n * Whether the user agent is Linux per the legacy behavior of\n * goog.userAgent.LINUX, which considered ChromeOS to also be\n * Linux.\n * @return {boolean}\n * @private\n */\ngoog.userAgent.isLegacyLinux_ = function() {\n 'use strict';\n return goog.labs.userAgent.platform.isLinux() ||\n goog.labs.userAgent.platform.isChromeOS();\n};\n\n\n/**\n * Whether the user agent is running on a Linux operating system.\n *\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\n * while goog.labs.userAgent.platform considers ChromeOS and\n * Linux to be different OSes.\n *\n * @type {boolean}\n */\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_LINUX :\n goog.userAgent.isLegacyLinux_();\n\n\n/**\n * @return {boolean} Whether the user agent is an X11 windowing system.\n * @private\n */\ngoog.userAgent.isX11_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return !!navigator &&\n goog.string.internal.contains(navigator['appVersion'] || '', 'X11');\n};\n\n\n/**\n * Whether the user agent is running on a X11 windowing system.\n * @type {boolean}\n */\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_X11 :\n goog.userAgent.isX11_();\n\n\n/**\n * Whether the user agent is running on Android.\n * @type {boolean}\n */\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_ANDROID :\n goog.labs.userAgent.platform.isAndroid();\n\n\n/**\n * Whether the user agent is running on an iPhone.\n * @type {boolean}\n */\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPHONE :\n goog.labs.userAgent.platform.isIphone();\n\n\n/**\n * Whether the user agent is running on an iPad.\n * @type {boolean}\n */\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPAD :\n goog.labs.userAgent.platform.isIpad();\n\n\n/**\n * Whether the user agent is running on an iPod.\n * @type {boolean}\n */\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPOD :\n goog.labs.userAgent.platform.isIpod();\n\n\n/**\n * Whether the user agent is running on iOS.\n * @type {boolean}\n */\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD) :\n goog.labs.userAgent.platform.isIos();\n\n/**\n * Whether the user agent is running on KaiOS.\n * @type {boolean}\n */\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_KAIOS :\n goog.labs.userAgent.platform.isKaiOS();\n\n\n/**\n * @return {string} The string that describes the version number of the user\n * agent.\n * @private\n */\ngoog.userAgent.determineVersion_ = function() {\n 'use strict';\n // All browsers have different ways to detect the version and they all have\n // different naming schemes.\n // version is a string rather than a number because it may contain 'b', 'a',\n // and so on.\n var version = '';\n var arr = goog.userAgent.getVersionRegexResult_();\n if (arr) {\n version = arr ? arr[1] : '';\n }\n\n if (goog.userAgent.IE) {\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\n // version. If it is identifying as a version lower than 9 we take the\n // documentMode as the version instead. IE8 has similar behavior.\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\n // uses documentMode 9.\n var docMode = goog.userAgent.getDocumentMode_();\n if (docMode != null && docMode > parseFloat(version)) {\n return String(docMode);\n }\n }\n\n return version;\n};\n\n\n/**\n * @return {?IArrayLike<string>|undefined} The version regex matches from\n * parsing the user\n * agent string. These regex statements must be executed inline so they can\n * be compiled out by the closure compiler with the rest of the useragent\n * detection logic when ASSUME_* is specified.\n * @private\n */\ngoog.userAgent.getVersionRegexResult_ = function() {\n 'use strict';\n var userAgent = goog.userAgent.getUserAgentString();\n if (goog.userAgent.GECKO) {\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.EDGE) {\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\n }\n if (goog.userAgent.IE) {\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.WEBKIT) {\n // WebKit/125.4\n return /WebKit\\/(\\S+)/.exec(userAgent);\n }\n if (goog.userAgent.OPERA) {\n // If none of the above browsers were detected but the browser is Opera, the\n // only string that is of interest is 'Version/<number>'.\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\n }\n return undefined;\n};\n\n\n/**\n * @return {number|undefined} Returns the document mode (for testing).\n * @private\n */\ngoog.userAgent.getDocumentMode_ = function() {\n 'use strict';\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\n var doc = goog.global['document'];\n return doc ? doc['documentMode'] : undefined;\n};\n\n\n/**\n * The version of the user agent. This is a string because it might contain\n * 'b' (as in beta) as well as multiple dots.\n * @type {string}\n */\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string} v1 Version of first item.\n * @param {string} v2 Version of second item.\n *\n * @return {number} 1 if first argument is higher\n * 0 if arguments are equal\n * -1 if second argument is higher.\n * @deprecated Use goog.string.compareVersions.\n */\ngoog.userAgent.compare = function(v1, v2) {\n 'use strict';\n return goog.string.internal.compareVersions(v1, v2);\n};\n\n\n/**\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\n * Calls to compareVersions are surprisingly expensive and, as a browser's\n * version number is unlikely to change during a session, we cache the results.\n * @const\n * @private\n */\ngoog.userAgent.isVersionOrHigherCache_ = {};\n\n\n/**\n * Whether the user agent version is higher or the same as the given version.\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\n * use the engine's version, not the browser's version number. For example,\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\n * Opera and Internet Explorer versions match the product release number.<br>\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\n * Webkit</a>\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the user agent version is higher or the same as\n * the given version.\n */\ngoog.userAgent.isVersionOrHigher = function(version) {\n 'use strict';\n return goog.userAgent.ASSUME_ANY_VERSION ||\n goog.reflect.cache(\n goog.userAgent.isVersionOrHigherCache_, version, function() {\n 'use strict';\n return goog.string.internal.compareVersions(\n goog.userAgent.VERSION, version) >= 0;\n });\n};\n\n\n/**\n * Whether the IE effective document mode is higher or the same as the given\n * document mode version.\n * NOTE: Only for IE, return false for another browser.\n *\n * @param {number} documentMode The document mode version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n */\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\n 'use strict';\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\n * @param {number} version The version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\n */\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\n\n\n/**\n * For IE version < 7, documentMode is undefined, so attempt to use the\n * CSS1Compat property to see if we are in standards mode. If we are in\n * standards mode, treat the browser version as the document mode. Otherwise,\n * IE is emulating version 5.\n *\n * NOTE(user): Support for IE < 7 is long gone, so this is now simplified.\n * It returns document.documentMode for IE and undefined for everything else.\n *\n * @type {number|undefined}\n * @const\n */\ngoog.userAgent.DOCUMENT_MODE = (function() {\n 'use strict';\n var doc = goog.global['document'];\n if (!doc || !goog.userAgent.IE) return undefined;\n // This must be an IE user agent.\n var documentMode = goog.userAgent.getDocumentMode_();\n if (documentMode) return documentMode;\n // The user agent version string begins with the major version.\n // Parse the major version and truncate anything following.\n var ieVersion = parseInt(goog.userAgent.VERSION, 10);\n return ieVersion || undefined;\n})();\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection (Browser).\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on rendering engine, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\n * goog.labs.userAgent.device respectively.)\n */\n\ngoog.module('goog.labs.userAgent.browser');\ngoog.module.declareLegacyNamespace();\n\nconst googAsserts = goog.require('goog.asserts');\nconst util = goog.require('goog.labs.userAgent.util');\nconst {AsyncValue, Version} = goog.require('goog.labs.userAgent.highEntropy.highEntropyValue');\nconst {compareVersions} = goog.require('goog.string.internal');\nconst {fullVersionList, hasFullVersionList} = goog.require('goog.labs.userAgent.highEntropy.highEntropyData');\n\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\n// functions.\n\n/**\n * A browser brand represents an opaque string that is used for making\n * brand-specific version checks in userAgentData.\n * @enum {string}\n */\nconst Brand = {\n /**\n * The browser brand for Android Browser.\n * Do not depend on the value of this string. Because Android Browser has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n ANDROID_BROWSER: 'Android Browser',\n /**\n * The browser brand for Chromium, including Chromium-based Edge and Opera.\n */\n CHROMIUM: 'Chromium',\n /**\n * The browser brand for Edge.\n * This brand can be used to get the version of both EdgeHTML and\n * Chromium-based Edge.\n */\n EDGE: 'Microsoft Edge',\n /**\n * The browser brand for Firefox.\n * Do not depend on the value of this string. Because Firefox has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n FIREFOX: 'Firefox',\n /**\n * The browser brand for Internet Explorer.\n * Do not depend on the value of this string. Because IE will never support\n * userAgentData, the value of this string should be treated as opaque (it's\n * used internally for legacy-userAgent fallback).\n */\n IE: 'Internet Explorer',\n /**\n * The browser brand for Opera.\n * This brand can be used to get the version of both Presto- and\n * Chromium-based Opera.\n */\n OPERA: 'Opera',\n /**\n * The browser brand for Safari.\n * Do not depend on the value of this string. Because Safari has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n SAFARI: 'Safari',\n /**\n * The browser brand for Silk.\n * See\n * https://docs.aws.amazon.com/silk/latest/developerguide/what-is-silk.html\n * Do not depend on the value of this string. Because Silk does not\n * identify itself in userAgentData yet, the value of this string is not\n * guaranteed to stay the same in future revisions.\n */\n SILK: 'Silk',\n};\nexports.Brand = Brand;\n\n/**\n * @return {boolean} Whether to use navigator.userAgentData to determine\n * browser's brand.\n */\nfunction useUserAgentDataBrand() {\n if (util.ASSUME_CLIENT_HINTS_SUPPORT) return true;\n const userAgentData = util.getUserAgentData();\n return !!userAgentData && userAgentData.brands.length > 0;\n}\n\n/**\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium based\n * Opera (Opera 15+) is detected as Chrome to avoid unnecessary special\n * casing.\n */\nfunction matchOpera() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Opera');\n}\n\n/** @return {boolean} Whether the user's browser is IE. */\nfunction matchIE() {\n if (useUserAgentDataBrand()) {\n // IE doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the user's browser is Edge. This refers to\n * EdgeHTML based Edge.\n */\nfunction matchEdgeHtml() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Edge');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nfunction matchEdgeChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.EDGE);\n }\n return util.matchUserAgent('Edg/');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nfunction matchOperaChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.OPERA);\n }\n return util.matchUserAgent('OPR');\n}\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nfunction matchFirefox() {\n // Firefox doesn't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Firefox') || util.matchUserAgent('FxiOS');\n}\n\n/** @return {boolean} Whether the user's browser is Safari. */\nfunction matchSafari() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Safari') &&\n !(matchChrome() || matchCoast() || matchOpera() || matchEdgeHtml() ||\n matchEdgeChromium() || matchOperaChromium() || matchFirefox() ||\n isSilk() || util.matchUserAgent('Android'));\n}\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nfunction matchCoast() {\n if (useUserAgentDataBrand()) {\n // Coast doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Coast');\n}\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nfunction matchIosWebview() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n // iOS Webview does not show up as Chrome or Safari.\n return (util.matchUserAgent('iPad') || util.matchUserAgent('iPhone')) &&\n !matchSafari() && !matchChrome() && !matchCoast() && !matchFirefox() &&\n util.matchUserAgent('AppleWebKit');\n}\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium browser. This\n * returns true for Chrome, Opera 15+, and Edge Chromium.\n */\nfunction matchChrome() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.CHROMIUM);\n }\n return ((util.matchUserAgent('Chrome') || util.matchUserAgent('CriOS')) &&\n !matchEdgeHtml()) ||\n isSilk();\n}\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nfunction matchAndroidBrowser() {\n // Android can appear in the user agent string for Chrome on Android.\n // This is not the Android standalone browser if it does.\n return util.matchUserAgent('Android') &&\n !(isChrome() || isFirefox() || isOpera() || isSilk());\n}\n\n/** @return {boolean} Whether the user's browser is Opera. */\nconst isOpera = matchOpera;\nexports.isOpera = isOpera;\n\n/** @return {boolean} Whether the user's browser is IE. */\nconst isIE = matchIE;\nexports.isIE = isIE;\n\n/** @return {boolean} Whether the user's browser is EdgeHTML based Edge. */\nconst isEdge = matchEdgeHtml;\nexports.isEdge = isEdge;\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nconst isEdgeChromium = matchEdgeChromium;\nexports.isEdgeChromium = isEdgeChromium;\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nconst isOperaChromium = matchOperaChromium;\nexports.isOperaChromium = isOperaChromium;\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nconst isFirefox = matchFirefox;\nexports.isFirefox = isFirefox;\n\n/** @return {boolean} Whether the user's browser is Safari. */\nconst isSafari = matchSafari;\nexports.isSafari = isSafari;\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nconst isCoast = matchCoast;\nexports.isCoast = isCoast;\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nconst isIosWebview = matchIosWebview;\nexports.isIosWebview = isIosWebview;\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium based browser (\n * Chrome, Blink-based Opera (15+) and Edge Chromium).\n */\nconst isChrome = matchChrome;\nexports.isChrome = isChrome;\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nconst isAndroidBrowser = matchAndroidBrowser;\nexports.isAndroidBrowser = isAndroidBrowser;\n\n/**\n * For more information, see:\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\n * @return {boolean} Whether the user's browser is Silk.\n */\nfunction isSilk() {\n // As of Silk 93, Silk does not identify itself in userAgentData.brands.\n // When Silk changes this behavior, update this method to call\n // matchUserAgentDataBrand (akin to isChrome, etc.)\n return util.matchUserAgent('Silk');\n}\nexports.isSilk = isSilk;\n\n/**\n * A helper function that returns a function mapping a list of candidate\n * version tuple keys to the first version string present under a key.\n * Ex:\n * <code>\n * // Arg extracted from \"Foo/1.2.3 Bar/0.2021\"\n * const mapVersion = createVersionMap([[\"Foo\", \"1.2.3\"], [\"Bar\", \"0.2021\"]]);\n * mapVersion([\"Bar\", \"Foo\"]); // returns \"0.2021\"\n * mapVersion([\"Baz\", \"Foo\"]); // returns \"1.2.3\"\n * mapVersion([\"Baz\", \"???\"]); // returns \"\"\n * </code>\n * @param {!Array<!Array<string>>} versionTuples Version tuples pre-extracted\n * from a user agent string.\n * @return {function(!Array<string>): string} The version string, or empty\n * string if it doesn't exist under the given key.\n */\nfunction createVersionMap(versionTuples) {\n // Construct a map for easy lookup.\n const versionMap = {};\n versionTuples.forEach((tuple) => {\n // Note that the tuple is of length three, but we only care about the\n // first two.\n const key = tuple[0];\n const value = tuple[1];\n versionMap[key] = value;\n });\n\n // Gives the value with the first key it finds, otherwise empty string.\n return (keys) => versionMap[keys.find((key) => key in versionMap)] || '';\n}\n\n/**\n * Returns the browser version.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and returns the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use\n * getVersionStringForLogging() or fullVersionOf() instead.\n *\n * @return {string} The browser version or empty string if version cannot be\n * determined. Note that for Internet Explorer, this returns the version of\n * the browser, not the version of the rendering engine. (IE 8 in\n * compatibility mode will return 8.0 rather than 7.0. To determine the\n * rendering engine version, look at document.documentMode instead. See\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\n * details.)\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (isIE()) {\n return getIEVersion(userAgentString);\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\n // See\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\n if (isOpera()) {\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\n // Opera uses 'OPR' for more recent UAs.\n return lookUpValueWithKeys(['Version', 'Opera']);\n }\n\n // Check Edge before Chrome since it has Chrome in the string.\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n }\n\n // Check Chromium Edge before Chrome since it has Chrome in the string.\n if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n\n // Check Silk before Chrome since it may have Chrome in its string and be\n // treated as Chrome.\n if (isSilk()) {\n return lookUpValueWithKeys(['Silk']);\n }\n\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n\n // Usually products browser versions are in the third tuple after \"Mozilla\"\n // and the engine.\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n}\nexports.getVersion = getVersion;\n\n/**\n * Returns whether the current browser's version is at least as high as the\n * given one.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and checks the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the browser version is higher or the same as the\n * given version.\n * @deprecated Use isAtLeast()/isAtMost() instead.\n */\nfunction isVersionOrHigher(version) {\n return compareVersions(getVersion(), version) >= 0;\n}\nexports.isVersionOrHigher = isVersionOrHigher;\n\n/**\n * A helper function to determine IE version. More information:\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\n * @param {string} userAgent the User-Agent.\n * @return {string}\n */\nfunction getIEVersion(userAgent) {\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\n // bug. Example UA:\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\n // like Gecko.\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\n const rv = /rv: *([\\d\\.]*)/.exec(userAgent);\n if (rv && rv[1]) {\n return rv[1];\n }\n\n let version = '';\n const msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\n if (msie && msie[1]) {\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\n // case, use the Trident version to determine the version of IE. For more\n // details, see the links above.\n const tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\n if (msie[1] == '7.0') {\n if (tridentVersion && tridentVersion[1]) {\n switch (tridentVersion[1]) {\n case '4.0':\n version = '8.0';\n break;\n case '5.0':\n version = '9.0';\n break;\n case '6.0':\n version = '10.0';\n break;\n case '7.0':\n version = '11.0';\n break;\n }\n } else {\n version = '7.0';\n }\n } else {\n version = msie[1];\n }\n }\n return version;\n}\n\n/**\n * A helper function to return the navigator.userAgent-supplied full version\n * number of the current browser or an empty string, based on whether the\n * current browser is the one specified.\n * @param {string} browser The brand whose version should be returned.\n * @return {string}\n */\nfunction getFullVersionFromUserAgentString(browser) {\n const userAgentString = util.getUserAgent();\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (browser === Brand.IE) {\n return isIE() ? getIEVersion(userAgentString) : '';\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n switch (browser) {\n case Brand.OPERA:\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\"\n // first. Opera uses 'OPR' for more recent UAs.\n if (isOpera()) {\n return lookUpValueWithKeys(['Version', 'Opera']);\n } else if (isOperaChromium()) {\n return lookUpValueWithKeys(['OPR']);\n }\n break;\n case Brand.EDGE:\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n } else if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n break;\n case Brand.CHROMIUM:\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n break;\n }\n\n // For the following browsers, the browser version is in the third tuple after\n // \"Mozilla\" and the engine.\n if ((browser === Brand.FIREFOX && isFirefox()) ||\n (browser === Brand.SAFARI && isSafari()) ||\n (browser === Brand.ANDROID_BROWSER && isAndroidBrowser()) ||\n (browser === Brand.SILK && isSilk())) {\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n }\n\n return '';\n}\n\n/**\n * Returns the major version of the given browser brand, or NaN if the current\n * browser is not the given brand.\n * Note that the major version number may be different depending on which\n * browser is specified. The returned value can be used to make browser version\n * comparisons using comparison operators.\n * @deprecated Use isAtLeast or isAtMost instead.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {number} The major version number associated with the current\n * browser under the given brand, or NaN if the current browser doesn't match\n * the given brand.\n */\nfunction versionOf(browser) {\n let versionParts;\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && browser !== Brand.SILK) {\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n if (!matchingBrand || !matchingBrand.version) {\n return NaN;\n }\n versionParts = matchingBrand.version.split('.');\n } else {\n const fullVersion = getFullVersionFromUserAgentString(browser);\n if (fullVersion === '') {\n return NaN;\n }\n versionParts = fullVersion.split('.');\n }\n if (versionParts.length === 0) {\n return NaN;\n }\n const majorVersion = versionParts[0];\n return Number(majorVersion); // Returns NaN if it is not parseable.\n}\nexports.versionOf = versionOf;\n\n/**\n * Returns true if the current browser matches the given brand and is at least\n * the given major version. The major version must be a whole number (i.e.\n * decimals should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at least the given version.\n */\nfunction isAtLeast(brand, majorVersion) {\n googAsserts.assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf(brand) >= majorVersion;\n}\nexports.isAtLeast = isAtLeast;\n\n/**\n * Returns true if the current browser matches the given brand and is at most\n * the given version. The major version must be a whole number (i.e. decimals\n * should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at most the given version.\n */\nfunction isAtMost(brand, majorVersion) {\n googAsserts.assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf(brand) <= majorVersion;\n}\nexports.isAtMost = isAtMost;\n\n/**\n * Loads the high-entropy browser brand/version data and wraps the correct\n * version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass HighEntropyBrandVersion {\n /**\n * @param {string} brand The brand whose version is retrieved in this\n * container.\n */\n constructor(brand) {\n /**\n * @const {string}\n * @private\n */\n this.brand_ = brand;\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n const loadedVersionList = fullVersionList.getIfLoaded();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n googAsserts.assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n return;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n const loadedVersionList = await fullVersionList.load();\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n googAsserts.assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n}\n\n/**\n * Wraps a version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass UserAgentStringFallbackBrandVersion {\n /**\n * @param {string} versionString\n */\n constructor(versionString) {\n /**\n * @const {!Version}\n * @private\n */\n this.version_ = new Version(versionString);\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n return this.version_;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n return this.version_;\n }\n}\n\n/**\n * Requests all full browser versions to be cached. When the returned promise\n * resolves, subsequent calls to `fullVersionOf(...).getIfLoaded()` will return\n * a value.\n *\n * This method should be avoided in favor of directly awaiting\n * `fullVersionOf(...).load()` where it is used.\n *\n * @return {!Promise<void>}\n */\nasync function loadFullVersions() {\n if (useUserAgentDataBrand() && hasFullVersionList()) {\n await fullVersionList.load();\n }\n}\nexports.loadFullVersions = loadFullVersions;\n\n/**\n * Returns an object that provides access to the full version string of the\n * current browser -- or undefined, based on whether the current browser matches\n * the requested browser brand. Note that the full version string is a\n * high-entropy value, and must be asynchronously loaded before it can be\n * accessed synchronously.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {!AsyncValue<!Version>|undefined} An object that can be used\n * to get or load the full version string as a high-entropy value, or\n * undefined if the current browser doesn't match the given brand.\n */\nfunction fullVersionOf(browser) {\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && hasFullVersionList()) {\n const data = util.getUserAgentData();\n // Operate under the assumption that the low-entropy and high-entropy lists\n // of brand/version pairs contain an identical set of brands. Therefore, if\n // the low-entropy list doesn't contain the given brand, return undefined.\n if (!data.brands.find(({brand}) => brand === browser)) {\n return undefined;\n }\n return new HighEntropyBrandVersion(browser);\n } else {\n const fullVersionFromUserAgentString =\n getFullVersionFromUserAgentString(browser);\n if (fullVersionFromUserAgentString === '') {\n return undefined;\n }\n return new UserAgentStringFallbackBrandVersion(\n fullVersionFromUserAgentString);\n }\n}\nexports.fullVersionOf = fullVersionOf;\n\n/**\n * Returns a version string for the current browser or undefined, based on\n * whether the current browser is the one specified.\n * This value should ONLY be used for logging/debugging purposes. Do not use it\n * to branch code paths. For comparing versions, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {string} The version as a string.\n */\nfunction getVersionStringForLogging(browser) {\n if (useUserAgentDataBrand()) {\n const fullVersionObj = fullVersionOf(browser);\n if (fullVersionObj) {\n const fullVersion = fullVersionObj.getIfLoaded();\n if (fullVersion) {\n return fullVersion.toVersionStringForLogging();\n }\n // No full version, return the major version instead.\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n // Checking for the existence of matchingBrand is not necessary because\n // the existence of fullVersionObj implies that there is already a\n // matching brand.\n googAsserts.assertExists(matchingBrand);\n return matchingBrand.version;\n }\n // If fullVersionObj is undefined, this doesn't mean that the full version\n // is unavailable, but rather that the current browser doesn't match the\n // input `browser` argument.\n return '';\n } else {\n return getFullVersionFromUserAgentString(browser);\n }\n}\nexports.getVersionStringForLogging = getVersionStringForLogging;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection.\n * @see http://en.wikipedia.org/wiki/User_agent\n * For more information on browser brand, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\n */\n\ngoog.module('goog.labs.userAgent.engine');\ngoog.module.declareLegacyNamespace();\n\nconst googArray = goog.require('goog.array');\nconst googString = goog.require('goog.string.internal');\nconst util = goog.require('goog.labs.userAgent.util');\n\n/**\n * @return {boolean} Whether the rendering engine is Presto.\n */\nfunction isPresto() {\n return util.matchUserAgent('Presto');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Trident.\n */\nfunction isTrident() {\n // IE only started including the Trident token in IE8.\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is EdgeHTML.\n */\nfunction isEdge() {\n return util.matchUserAgent('Edge');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is WebKit. This will return\n * true for Chrome, Blink-based Opera (15+), Edge Chromium and Safari.\n */\nfunction isWebKit() {\n return util.matchUserAgentIgnoreCase('WebKit') && !isEdge();\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Gecko.\n */\nfunction isGecko() {\n return util.matchUserAgent('Gecko') && !isWebKit() && !isTrident() &&\n !isEdge();\n}\n\n/**\n * @return {string} The rendering engine's version or empty string if version\n * can't be determined.\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n if (userAgentString) {\n const tuples = util.extractVersionTuples(userAgentString);\n\n const engineTuple = getEngineTuple(tuples);\n if (engineTuple) {\n // In Gecko, the version string is either in the browser info or the\n // Firefox version. See Gecko user agent string reference:\n // http://goo.gl/mULqa\n if (engineTuple[0] == 'Gecko') {\n return getVersionForKey(tuples, 'Firefox');\n }\n\n return engineTuple[1];\n }\n\n // MSIE has only one version identifier, and the Trident version is\n // specified in the parenthetical. IE Edge is covered in the engine tuple\n // detection.\n const browserTuple = tuples[0];\n let info;\n if (browserTuple && (info = browserTuple[2])) {\n const match = /Trident\\/([^\\s;]+)/.exec(info);\n if (match) {\n return match[1];\n }\n }\n }\n return '';\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\n * found.\n */\nfunction getEngineTuple(tuples) {\n if (!isEdge()) {\n return tuples[1];\n }\n for (let i = 0; i < tuples.length; i++) {\n const tuple = tuples[i];\n if (tuple[0] == 'Edge') {\n return tuple;\n }\n }\n}\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the rendering engine version is higher or the same\n * as the given version.\n */\nfunction isVersionOrHigher(version) {\n return googString.compareVersions(getVersion(), version) >= 0;\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Version tuples.\n * @param {string} key The key to look for.\n * @return {string} The version string of the given key, if present.\n * Otherwise, the empty string.\n */\nfunction getVersionForKey(tuples, key) {\n // TODO(nnaze): Move to util if useful elsewhere.\n\n const pair = googArray.find(tuples, function(pair) {\n return key == pair[0];\n });\n\n return pair && pair[1] || '';\n}\n\nexports = {\n getVersion,\n isEdge,\n isGecko,\n isPresto,\n isTrident,\n isVersionOrHigher,\n isWebKit,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Wrapper class for handling XmlHttpRequests.\n *\n * One off requests can be sent through goog.net.XhrIo.send() or an\n * instance can be created to send multiple requests. Each request uses its\n * own XmlHttpRequest object and handles clearing of the event callback to\n * ensure no leaks.\n *\n * XhrIo is event based, it dispatches events on success, failure, finishing,\n * ready-state change, or progress (download and upload).\n *\n * The ready-state or timeout event fires first, followed by\n * a generic completed event. Then the abort, error, or success event\n * is fired as appropriate. Progress events are fired as they are\n * received. Lastly, the ready event will fire to indicate that the\n * object may be used to make another request.\n *\n * The error event may also be called before completed and\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\n *\n * This class does not support multiple requests, queuing, or prioritization.\n *\n * When progress events are supported by the browser, and progress is\n * enabled via .setProgressEventsEnabled(true), the\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\n * will be fired for download and upload progress respectively.\n */\n\n\ngoog.provide('goog.net.XhrIo');\ngoog.provide('goog.net.XhrIo.ResponseType');\n\ngoog.require('goog.Timer');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json.hybrid');\ngoog.require('goog.log');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.HttpStatus');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.uri.utils');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.net.XhrLike');\ngoog.requireType('goog.net.XmlHttpFactory');\n\ngoog.scope(function() {\n\n'use strict';\n/**\n * Basic class for handling XMLHttpRequests.\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\n * creating XMLHttpRequest objects.\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\n 'use strict';\n XhrIo.base(this, 'constructor');\n\n /**\n * Map of default headers to add to every request, use:\n * XhrIo.headers.set(name, value)\n * @type {!Map<string,string>}\n */\n this.headers = new Map();\n\n /**\n * Optional XmlHttpFactory\n * @private {goog.net.XmlHttpFactory}\n */\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\n\n /**\n * Whether XMLHttpRequest is active. A request is active from the time send()\n * is called until onReadyStateChange() is complete, or error() or abort()\n * is called.\n * @private {boolean}\n */\n this.active_ = false;\n\n /**\n * The XMLHttpRequest object that is being used for the transfer.\n * @private {?goog.net.XhrLike.OrNative}\n */\n this.xhr_ = null;\n\n /**\n * The options to use with the current XMLHttpRequest object.\n * @private {?Object}\n */\n this.xhrOptions_ = null;\n\n /**\n * Last URL that was requested.\n * @private {string|goog.Uri}\n */\n this.lastUri_ = '';\n\n /**\n * Method for the last request.\n * @private {string}\n */\n this.lastMethod_ = '';\n\n /**\n * Last error code.\n * @private {!goog.net.ErrorCode}\n */\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n\n /**\n * Last error message.\n * @private {Error|string}\n */\n this.lastError_ = '';\n\n /**\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\n * happen in IE when it does a synchronous load and one error is handled in\n * the ready state change and one is handled due to send() throwing an\n * exception.\n * @private {boolean}\n */\n this.errorDispatched_ = false;\n\n /**\n * Used to make sure we don't fire the complete event from inside a send call.\n * @private {boolean}\n */\n this.inSend_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.open.\n * @private {boolean}\n */\n this.inOpen_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.abort.\n * @private {boolean}\n */\n this.inAbort_ = false;\n\n /**\n * Number of milliseconds after which an incomplete request will be aborted\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\n * is set.\n * @private {number}\n */\n this.timeoutInterval_ = 0;\n\n /**\n * Timer to track request timeout.\n * @private {?number}\n */\n this.timeoutId_ = null;\n\n /**\n * The requested type for the response. The empty string means use the default\n * XHR behavior.\n * @private {goog.net.XhrIo.ResponseType}\n */\n this.responseType_ = ResponseType.DEFAULT;\n\n /**\n * Whether a \"credentialed\" request is to be sent (one that is aware of\n * cookies and authentication). This is applicable only for cross-domain\n * requests and more recent browsers that support this part of the HTTP Access\n * Control standard.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\n *\n * @private {boolean}\n */\n this.withCredentials_ = false;\n\n /**\n * Whether progress events are enabled for this request. This is\n * disabled by default because setting a progress event handler\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\n * even in cases where a pre-flight request would not otherwise be\n * sent.\n *\n * @see http://xhr.spec.whatwg.org/#security-considerations\n *\n * Note that this can cause problems for Firefox 22 and below, as an\n * older \"LSProgressEvent\" will be dispatched by the browser. That\n * progress event is no longer supported, and can lead to failures,\n * including throwing exceptions.\n *\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\n * @see b/23469793\n *\n * @private {boolean}\n */\n this.progressEventsEnabled_ = false;\n\n /**\n * True if we can use XMLHttpRequest's timeout directly.\n * @private {boolean}\n */\n this.useXhr2Timeout_ = false;\n\n /**\n * Specification for Trust Token operations (issuance, signing, and\n * redemption).\n * @private {?TrustTokenAttributeType}\n */\n this.trustToken_ = null;\n};\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\n\nconst XhrIo = goog.net.XhrIo;\n\n/**\n * Response types that may be requested for XMLHttpRequests.\n * @enum {string}\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\n */\ngoog.net.XhrIo.ResponseType = {\n DEFAULT: '',\n TEXT: 'text',\n DOCUMENT: 'document',\n // Not supported as of Chrome 10.0.612.1 dev\n BLOB: 'blob',\n ARRAY_BUFFER: 'arraybuffer',\n};\n\nconst ResponseType = goog.net.XhrIo.ResponseType;\n\n\n/**\n * A reference to the XhrIo logger\n * @private {?goog.log.Logger}\n * @const\n */\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\n\n\n/**\n * The Content-Type HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\n\n\n/**\n * The Content-Transfer-Encoding HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\n\n\n/**\n * The pattern matching the 'http' and 'https' URI schemes\n * @type {!RegExp}\n */\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\n\nconst HTTP_SCHEME_PATTERN = goog.net.XhrIo.HTTP_SCHEME_PATTERN;\n\n\n/**\n * The methods that typically come along with form data. We set different\n * headers depending on whether the HTTP action is one of these.\n * @type {!Array<string>}\n */\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\n\n\n/**\n * The Content-Type HTTP header value for a url-encoded form\n * @type {string}\n */\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\n 'application/x-www-form-urlencoded;charset=utf-8';\n\n\n/**\n * The XMLHttpRequest Level two timeout delay ms property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\n\n\n/**\n * The XMLHttpRequest Level two ontimeout handler property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\n\n\n/**\n * All non-disposed instances of goog.net.XhrIo created\n * by {@link goog.net.XhrIo.send} are in this Array.\n * @see goog.net.XhrIo.cleanup\n * @private {!Array<!goog.net.XhrIo>}\n */\ngoog.net.XhrIo.sendInstances_ = [];\n\n\n/**\n * Static send that creates a short lived instance of XhrIo to send the\n * request.\n * @see goog.net.XhrIo.cleanup\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\n * for when request is complete.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\n * incomplete request will be aborted; 0 means no timeout is set.\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\n * @return {!goog.net.XhrIo} The sent XhrIo.\n */\ngoog.net.XhrIo.send = function(\n url, opt_callback, opt_method, opt_content, opt_headers,\n opt_timeoutInterval, opt_withCredentials) {\n 'use strict';\n const x = new goog.net.XhrIo();\n goog.net.XhrIo.sendInstances_.push(x);\n if (opt_callback) {\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\n }\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\n if (opt_timeoutInterval) {\n x.setTimeoutInterval(opt_timeoutInterval);\n }\n if (opt_withCredentials) {\n x.setWithCredentials(opt_withCredentials);\n }\n x.send(url, opt_method, opt_content, opt_headers);\n return x;\n};\n\n\n/**\n * Disposes all non-disposed instances of goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send}.\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\n * it creates when the request completes or fails. However, if\n * the request never completes, then the goog.net.XhrIo is not disposed.\n * This can occur if the window is unloaded before the request completes.\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\n * it creates and make the client of {@link goog.net.XhrIo.send} be\n * responsible for disposing it in this case. However, this makes things\n * significantly more complicated for the client, and the whole point\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\n * Clients of {@link goog.net.XhrIo.send} should call\n * {@link goog.net.XhrIo.cleanup} when doing final\n * cleanup on window unload.\n */\ngoog.net.XhrIo.cleanup = function() {\n 'use strict';\n const instances = goog.net.XhrIo.sendInstances_;\n while (instances.length) {\n instances.pop().dispose();\n }\n};\n\n\n/**\n * Installs exception protection for all entry point introduced by\n * goog.net.XhrIo instances which are not protected by\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\n * {@link goog.events.protectBrowserEventEntryPoint}.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point(s).\n */\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n errorHandler.protectEntryPoint(\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n};\n\n\n/**\n * Disposes of the specified goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send} and removes it from\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\n 'use strict';\n this.dispose();\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\n};\n\n\n/**\n * Returns the number of milliseconds after which an incomplete request will be\n * aborted, or 0 if no timeout is set.\n * @return {number} Timeout interval in milliseconds.\n */\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\n 'use strict';\n return this.timeoutInterval_;\n};\n\n\n/**\n * Sets the number of milliseconds after which an incomplete request will be\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\n * timeout is set.\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\n */\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\n 'use strict';\n this.timeoutInterval_ = Math.max(0, ms);\n};\n\n\n/**\n * Sets the desired type for the response. At time of writing, this is only\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\n *\n * If this is used, the response may only be accessed via {@link #getResponse}.\n *\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\n */\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\n 'use strict';\n this.responseType_ = type;\n};\n\n\n/**\n * Gets the desired type for the response.\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getResponseType = function() {\n 'use strict';\n return this.responseType_;\n};\n\n\n/**\n * Sets whether a \"credentialed\" request that is aware of cookie and\n * authentication information should be made. This option is only supported by\n * browsers that support HTTP Access Control. As of this writing, this option\n * is not supported in IE.\n *\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\n * request.\n */\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\n 'use strict';\n this.withCredentials_ = withCredentials;\n};\n\n\n/**\n * Gets whether a \"credentialed\" request is to be sent.\n * @return {boolean} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\n 'use strict';\n return this.withCredentials_;\n};\n\n\n/**\n * Sets whether progress events are enabled for this request. Note\n * that progress events require pre-flight OPTIONS request handling\n * for CORS requests, and may cause trouble with older browsers. See\n * progressEventsEnabled_ for details.\n * @param {boolean} enabled Whether progress events should be enabled.\n */\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\n 'use strict';\n this.progressEventsEnabled_ = enabled;\n};\n\n\n/**\n * Gets whether progress events are enabled.\n * @return {boolean} Whether progress events are enabled for this request.\n */\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\n 'use strict';\n return this.progressEventsEnabled_;\n};\n\n/**\n * Specify a Trust Tokens operation to execute alongside the request.\n * @param {!TrustTokenAttributeType} trustToken a Trust Tokens operation to\n * execute.\n */\ngoog.net.XhrIo.prototype.setTrustToken = function(trustToken) {\n 'use strict';\n this.trustToken_ = trustToken;\n};\n\n/**\n * Instance send that actually uses XMLHttpRequest to make a server call.\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters for opt_headers.\n */\ngoog.net.XhrIo.prototype.send = function(\n url, opt_method, opt_content, opt_headers) {\n 'use strict';\n if (this.xhr_) {\n throw new Error(\n '[goog.net.XhrIo] Object is active with another request=' +\n this.lastUri_ + '; newUri=' + url);\n }\n\n const method = opt_method ? opt_method.toUpperCase() : 'GET';\n\n this.lastUri_ = url;\n this.lastError_ = '';\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n this.lastMethod_ = method;\n this.errorDispatched_ = false;\n this.active_ = true;\n\n // Use the factory to create the XHR object and options\n this.xhr_ = this.createXhr();\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\n goog.net.XmlHttp.getOptions();\n\n // Set up the onreadystatechange callback\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\n\n // Set up upload/download progress events, if progress events are supported.\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\n this.xhr_.onprogress = goog.bind(function(e) {\n 'use strict';\n this.onProgressHandler_(e, true);\n }, this);\n if (this.xhr_.upload) {\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\n }\n }\n\n /**\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\n * is generally permission denied\n */\n try {\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\n this.inOpen_ = true;\n this.xhr_.open(method, String(url), true); // Always async!\n this.inOpen_ = false;\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n return;\n }\n\n // We can't use null since this won't allow requests with form data to have a\n // content length specified which will cause some proxies to return a 411\n // error.\n const content = opt_content || '';\n\n const headers = new Map(this.headers);\n\n // Add headers specific to this request\n if (opt_headers) {\n if (Object.getPrototypeOf(opt_headers) === Object.prototype) {\n for (let key in opt_headers) {\n headers.set(key, opt_headers[key]);\n }\n } else if (\n typeof opt_headers.keys === 'function' &&\n typeof opt_headers.get === 'function') {\n for (const key of opt_headers.keys()) {\n headers.set(key, opt_headers.get(key));\n }\n } else {\n throw new Error(\n 'Unknown input type for opt_headers: ' + String(opt_headers));\n }\n }\n\n // Find whether a content type header is set, ignoring case.\n // HTTP header names are case-insensitive. See:\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n const contentTypeKey =\n Array.from(headers.keys())\n .find(\n header => goog.string.caseInsensitiveEquals(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header));\n\n const contentIsFormData =\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\n !contentTypeKey && !contentIsFormData) {\n // For requests typically with form data, default to the url-encoded form\n // content type unless this is a FormData request. For FormData,\n // the browser will automatically add a multipart/form-data content type\n // with an appropriate multipart boundary.\n headers.set(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\n }\n\n // Add the headers to the Xhr object\n for (const [key, value] of headers) {\n this.xhr_.setRequestHeader(key, value);\n }\n\n if (this.responseType_) {\n this.xhr_.responseType = this.responseType_;\n }\n // Set xhr_.withCredentials only when the value is different, or else in\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\n if ('withCredentials' in this.xhr_ &&\n this.xhr_.withCredentials !== this.withCredentials_) {\n this.xhr_.withCredentials = this.withCredentials_;\n }\n\n if ('setTrustToken' in this.xhr_ && this.trustToken_) {\n try {\n this.xhr_.setTrustToken(this.trustToken_);\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error SetTrustToken: ' + err.message));\n }\n }\n /**\n * Try to send the request, or other wise report an error (404 not found).\n */\n try {\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\n if (this.timeoutInterval_ > 0) {\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\n goog.log.fine(\n this.logger_,\n this.formatMsg_(\n 'Will abort after ' + this.timeoutInterval_ +\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\n if (this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\n goog.bind(this.timeout_, this);\n } else {\n this.timeoutId_ =\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\n }\n }\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\n this.inSend_ = true;\n this.xhr_.send(content);\n this.inSend_ = false;\n\n } catch (err) {\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n }\n};\n\n\n/**\n * Determines if the argument is an XMLHttpRequest that supports the level 2\n * timeout value and event.\n *\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\n * handler. Perhaps the confusion in the bug referenced below hasn't\n * entirely been resolved.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\n *\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\n * @return {boolean} True if the request supports level 2 timeout.\n * @private\n */\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\n 'use strict';\n return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&\n typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&\n xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;\n};\n\n\n/**\n * Creates a new XHR object.\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\n * @protected\n */\ngoog.net.XhrIo.prototype.createXhr = function() {\n 'use strict';\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\n goog.net.XmlHttp();\n};\n\n\n/**\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\n * the request.\n * @private\n */\ngoog.net.XhrIo.prototype.timeout_ = function() {\n 'use strict';\n if (typeof goog == 'undefined') {\n // If goog is undefined then the callback has occurred as the application\n // is unloading and will error. Thus we let it silently fail.\n } else if (this.xhr_) {\n this.lastError_ =\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\n this.abort(goog.net.ErrorCode.TIMEOUT);\n }\n};\n\n\n/**\n * Something errorred, so inactivate, fire error callback and clean up\n * @param {goog.net.ErrorCode} errorCode The error code.\n * @param {Error} err The error object.\n * @private\n */\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\n 'use strict';\n this.active_ = false;\n if (this.xhr_) {\n this.inAbort_ = true;\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\n this.inAbort_ = false;\n }\n this.lastError_ = err;\n this.lastErrorCode_ = errorCode;\n this.dispatchErrors_();\n this.cleanUpXhr_();\n};\n\n\n/**\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\n * not dispatch multiple error events.\n * @private\n */\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\n 'use strict';\n if (!this.errorDispatched_) {\n this.errorDispatched_ = true;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ERROR);\n }\n};\n\n\n/**\n * Abort the current XMLHttpRequest\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\n * defaults to ABORT.\n */\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\n 'use strict';\n if (this.xhr_ && this.active_) {\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ABORT);\n this.cleanUpXhr_();\n }\n};\n\n\n/**\n * Nullifies all callbacks to reduce risks of leaks.\n * @override\n * @protected\n */\ngoog.net.XhrIo.prototype.disposeInternal = function() {\n 'use strict';\n if (this.xhr_) {\n // We explicitly do not call xhr_.abort() unless active_ is still true.\n // This is to avoid unnecessarily aborting a successful request when\n // dispose() is called in a callback triggered by a complete response, but\n // in which browser cleanup has not yet finished.\n // (See http://b/issue?id=1684217.)\n if (this.active_) {\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n }\n this.cleanUpXhr_(true);\n }\n\n XhrIo.base(this, 'disposeInternal');\n};\n\n\n/**\n * Internal handler for the XHR object's readystatechange event. This method\n * checks the status and the readystate and fires the correct callbacks.\n * If the request has ended, the handlers are cleaned up and the XHR object is\n * nullified.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\n 'use strict';\n if (this.isDisposed()) {\n // This method is the target of an untracked goog.Timer.callOnce().\n return;\n }\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\n // Were not being called from within a call to this.xhr_.send\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\n this.onReadyStateChangeEntryPoint_();\n } else {\n this.onReadyStateChangeHelper_();\n }\n};\n\n\n/**\n * Used to protect the onreadystatechange handler entry point. Necessary\n * as {#onReadyStateChange_} maybe called from within send or abort, this\n * method is only called when {#onReadyStateChange_} is called as an\n * entry point.\n * {@see #protectEntryPoints}\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\n 'use strict';\n this.onReadyStateChangeHelper_();\n};\n\n\n/**\n * Helper for {@link #onReadyStateChange_}. This is used so that\n * entry point calls to {@link #onReadyStateChange_} can be routed through\n * {@link #onReadyStateChangeEntryPoint_}.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\n 'use strict';\n if (!this.active_) {\n // can get called inside abort call\n return;\n }\n\n if (typeof goog == 'undefined') {\n // NOTE(user): If goog is undefined then the callback has occurred as the\n // application is unloading and will error. Thus we let it silently fail.\n\n } else if (\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\n this.getStatus() == 2) {\n // NOTE(user): In IE if send() errors on a *local* request the readystate\n // is still changed to COMPLETE. We need to ignore it and allow the\n // try/catch around send() to pick up the error.\n goog.log.fine(\n this.logger_,\n this.formatMsg_('Local request error detected and ignored'));\n\n } else {\n // In IE when the response has been cached we sometimes get the callback\n // from inside the send call and this usually breaks code that assumes that\n // XhrIo is asynchronous. If that is the case we delay the callback\n // using a timer.\n if (this.inSend_ &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\n return;\n }\n\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\n\n // readyState indicates the transfer has finished\n if (this.isComplete()) {\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\n\n this.active_ = false;\n\n try {\n // Call the specific callbacks for success or failure. Only call the\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\n if (this.isSuccess()) {\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.SUCCESS);\n } else {\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\n this.lastError_ =\n this.getStatusText() + ' [' + this.getStatus() + ']';\n this.dispatchErrors_();\n }\n } finally {\n this.cleanUpXhr_();\n }\n }\n }\n};\n\n\n/**\n * Internal handler for the XHR object's onprogress event. Fires both a generic\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\n * allow specific binding for each XHR progress event.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\n * event should be dispatched.\n * @private\n */\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\n 'use strict';\n goog.asserts.assert(\n e.type === goog.net.EventType.PROGRESS,\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\n this.dispatchEvent(\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\n this.dispatchEvent(goog.net.XhrIo.buildProgressEvent_(\n e,\n opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\n goog.net.EventType.UPLOAD_PROGRESS));\n};\n\n\n/**\n * Creates a representation of the native ProgressEvent. IE doesn't support\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {!goog.net.EventType} eventType The type of the event.\n * @return {!ProgressEvent} The progress event.\n * @private\n */\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\n 'use strict';\n return /** @type {!ProgressEvent} */ ({\n type: eventType,\n lengthComputable: e.lengthComputable,\n loaded: e.loaded,\n total: e.total,\n });\n};\n\n\n/**\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\n * object.\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\n * fire any events).\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\n 'use strict';\n if (this.xhr_) {\n // Cancel any pending timeout event handler.\n this.cleanUpTimeoutTimer_();\n\n // Save reference so we can mark it as closed after the READY event. The\n // READY event may trigger another request, thus we must nullify this.xhr_\n const xhr = this.xhr_;\n const clearedOnReadyStateChange =\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\n goog.nullFunction :\n null;\n this.xhr_ = null;\n this.xhrOptions_ = null;\n\n if (!opt_fromDispose) {\n this.dispatchEvent(goog.net.EventType.READY);\n }\n\n try {\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\n // allow you to set the onreadystatechange to NULL so nullFunction is\n // used.\n xhr.onreadystatechange = clearedOnReadyStateChange;\n } catch (e) {\n // This seems to occur with a Gears HTTP request. Delayed the setting of\n // this onreadystatechange until after READY is sent out and catching the\n // error to see if we can track down the problem.\n goog.log.error(\n this.logger_,\n 'Problem encountered resetting onreadystatechange: ' + e.message);\n }\n }\n};\n\n\n/**\n * Make sure the timeout timer isn't running.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\n 'use strict';\n if (this.xhr_ && this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\n }\n if (this.timeoutId_) {\n goog.Timer.clear(this.timeoutId_);\n this.timeoutId_ = null;\n }\n};\n\n\n/**\n * @return {boolean} Whether there is an active request.\n */\ngoog.net.XhrIo.prototype.isActive = function() {\n 'use strict';\n return !!this.xhr_;\n};\n\n\n/**\n * @return {boolean} Whether the request has completed.\n */\ngoog.net.XhrIo.prototype.isComplete = function() {\n 'use strict';\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n};\n\n\n/**\n * @return {boolean} Whether the request completed with a success.\n */\ngoog.net.XhrIo.prototype.isSuccess = function() {\n 'use strict';\n const status = this.getStatus();\n // A zero status code is considered successful for local files.\n return goog.net.HttpStatus.isSuccess(status) ||\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\n};\n\n\n/**\n * @return {boolean} whether the effective scheme of the last URI that was\n * fetched was 'http' or 'https'.\n * @private\n */\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\n 'use strict';\n const scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\n return HTTP_SCHEME_PATTERN.test(scheme);\n};\n\n\n/**\n * Get the readystate from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\n */\ngoog.net.XhrIo.prototype.getReadyState = function() {\n 'use strict';\n return this.xhr_ ?\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\n goog.net.XmlHttp.ReadyState.UNINITIALIZED;\n};\n\n\n/**\n * Get the status from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {number} Http status.\n */\ngoog.net.XhrIo.prototype.getStatus = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.status :\n -1;\n } catch (e) {\n return -1;\n }\n};\n\n\n/**\n * Get the status text from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {string} Status text.\n */\ngoog.net.XhrIo.prototype.getStatusText = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.statusText :\n '';\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the last Uri that was requested\n * @return {string} Last Uri.\n */\ngoog.net.XhrIo.prototype.getLastUri = function() {\n 'use strict';\n return String(this.lastUri_);\n};\n\n\n/**\n * Get the response text from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {string} Result from the server, or '' if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseText = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseText : '';\n } catch (e) {\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\n // states that responseText should return '' (and responseXML null)\n // when the state is not LOADING or DONE. Instead, IE can\n // throw unexpected exceptions, for example when a request is aborted\n // or no data is available yet.\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the response body from the Xhr object. This property is only available\n * in IE since version 7 according to MSDN:\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\n * Will only return correct result when called from the context of a callback.\n *\n * One option is to construct a VBArray from the returned object and convert\n * it to a JavaScript array using the toArray method:\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\n * This will result in an array of numbers in the range of [0..255]\n *\n * Another option is to use the VBScript CStr method to convert it into a\n * string as outlined in http://stackoverflow.com/questions/1919972\n *\n * @return {Object} Binary result from the server or null if not available.\n */\ngoog.net.XhrIo.prototype.getResponseBody = function() {\n 'use strict';\n try {\n if (this.xhr_ && 'responseBody' in this.xhr_) {\n return this.xhr_['responseBody'];\n }\n } catch (e) {\n // IE can throw unexpected exceptions, for example when a request is aborted\n // or no data is yet available.\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\n }\n return null;\n};\n\n\n/**\n * Get the response XML from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {Document} The DOM Document representing the XML file, or null\n * if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseXml = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseXML : null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the response and evaluates it as JSON from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\n * stripping of the response before parsing. This needs to be set only if\n * your backend server prepends the same prefix string to the JSON response.\n * @throws Error if the response text is invalid JSON.\n * @return {Object|undefined} JavaScript object.\n */\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\n 'use strict';\n if (!this.xhr_) {\n return undefined;\n }\n\n let responseText = this.xhr_.responseText;\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\n responseText = responseText.substring(opt_xssiPrefix.length);\n }\n\n return goog.json.hybrid.parse(responseText);\n};\n\n\n/**\n * Get the response as the type specificed by {@link #setResponseType}. At time\n * of writing, this is only directly supported in very recent versions of WebKit\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\n * try to emulate it.\n *\n * Emulating the response means following the rules laid out at\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\n *\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\n * response types of DEFAULT or TEXT may be used, and the response returned will\n * be the text response.\n *\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\n * response returned will be either the text response or the Mozilla\n * implementation of the array buffer response.\n *\n * On browsers will full support, any valid response type supported by the\n * browser may be used, and the response provided by the browser will be\n * returned.\n *\n * @return {*} The response.\n */\ngoog.net.XhrIo.prototype.getResponse = function() {\n 'use strict';\n try {\n if (!this.xhr_) {\n return null;\n }\n if ('response' in this.xhr_) {\n return this.xhr_.response;\n }\n switch (this.responseType_) {\n case ResponseType.DEFAULT:\n case ResponseType.TEXT:\n return this.xhr_.responseText;\n // DOCUMENT and BLOB don't need to be handled here because they are\n // introduced in the same spec that adds the .response field, and would\n // have been caught above.\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\n // implemented using a draft spec rather than the final spec.\n case ResponseType.ARRAY_BUFFER:\n if ('mozResponseArrayBuffer' in this.xhr_) {\n return this.xhr_.mozResponseArrayBuffer;\n }\n }\n // Fell through to a response type that is not supported on this browser.\n goog.log.error(\n this.logger_,\n 'Response type ' + this.responseType_ + ' is not ' +\n 'supported on this browser');\n return null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object\n * Will only return correct result when called from the context of a callback\n * and the request has completed\n * @param {string} key The name of the response-header to retrieve.\n * @return {string|undefined} The value of the response-header named key.\n */\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\n 'use strict';\n if (!this.xhr_ || !this.isComplete()) {\n return undefined;\n }\n\n const value = this.xhr_.getResponseHeader(key);\n return value === null ? undefined : value;\n};\n\n\n/**\n * Gets the text of all the headers in the response.\n * Will only return correct result when called from the context of a callback\n * and the request has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\n 'use strict';\n // getAllResponseHeaders can return null if no response has been received,\n // ensure we always return an empty string.\n return this.xhr_ && this.isComplete() ?\n (this.xhr_.getAllResponseHeaders() || '') :\n '';\n};\n\n\n/**\n * Returns all response headers as a key-value map.\n * Multiple values for the same header key can be combined into one,\n * separated by a comma and a space.\n * Note that the native getResponseHeader method for retrieving a single header\n * does a case insensitive match on the header name. This method does not\n * include any case normalization logic, it will just return a key-value\n * representation of the headers.\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\n * @return {!Object<string, string>} An object with the header keys as keys\n * and header values as values.\n */\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\n 'use strict';\n // TODO(user): Make this function parse headers as per the spec\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\n\n const headersObject = {};\n const headersArray = this.getAllResponseHeaders().split('\\r\\n');\n for (let i = 0; i < headersArray.length; i++) {\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\n continue;\n }\n const keyValue =\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\n const key = keyValue[0];\n let value = keyValue[1];\n\n if (typeof value !== 'string') {\n // There must be a value but it can be the empty string.\n continue;\n }\n\n // Whitespace at the start and end of the value is meaningless.\n value = value.trim();\n // The key should not contain whitespace but we currently ignore that.\n\n const values = headersObject[key] || [];\n headersObject[key] = values;\n values.push(value);\n }\n\n return goog.object.map(headersObject, function(values) {\n 'use strict';\n return values.join(', ');\n });\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object.\n * As opposed to {@link #getResponseHeader}, this method does not require that\n * the request has completed.\n * @param {string} key The name of the response-header to retrieve.\n * @return {?string} The value of the response-header, or null if it is\n * unavailable.\n */\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\n 'use strict';\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\n};\n\n\n/**\n * Gets the text of all the headers in the response. As opposed to\n * {@link #getAllResponseHeaders}, this method does not require that the request\n * has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\n 'use strict';\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\n};\n\n\n/**\n * Get the last error message\n * @return {!goog.net.ErrorCode} Last error code.\n */\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\n 'use strict';\n return this.lastErrorCode_;\n};\n\n\n/**\n * Get the last error message\n * @return {string} Last error message.\n */\ngoog.net.XhrIo.prototype.getLastError = function() {\n 'use strict';\n return typeof this.lastError_ === 'string' ? this.lastError_ :\n String(this.lastError_);\n};\n\n\n/**\n * Adds the last method, status and URI to the message. This is used to add\n * this information to the logging calls.\n * @param {string} msg The message text that we want to add the extra text to.\n * @return {string} The message with the extra text appended.\n * @private\n */\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\n 'use strict';\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\n this.getStatus() + ']';\n};\n\n\n// Register the xhr handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n });\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A patched, standardized event object for browser events.\n *\n * <pre>\n * The patched event object contains the following members:\n * - type {string} Event type, e.g. 'click'\n * - target {Object} The element that actually triggered the event\n * - currentTarget {Object} The element the listener is attached to\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\n * - offsetX {number} X-coordinate relative to target\n * - offsetY {number} Y-coordinate relative to target\n * - clientX {number} X-coordinate relative to viewport\n * - clientY {number} Y-coordinate relative to viewport\n * - screenX {number} X-coordinate relative to the edge of the screen\n * - screenY {number} Y-coordinate relative to the edge of the screen\n * - button {number} Mouse button. Use isButton() to test.\n * - keyCode {number} Key-code\n * - ctrlKey {boolean} Was ctrl key depressed\n * - altKey {boolean} Was alt key depressed\n * - shiftKey {boolean} Was shift key depressed\n * - metaKey {boolean} Was meta key depressed\n * - pointerId {number} Pointer ID\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\n * - defaultPrevented {boolean} Whether the default action has been prevented\n * - state {Object} History state object\n *\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\n * key and character code use {@link goog.events.KeyHandler}.\n * </pre>\n */\n\ngoog.provide('goog.events.BrowserEvent');\ngoog.provide('goog.events.BrowserEvent.MouseButton');\ngoog.provide('goog.events.BrowserEvent.PointerType');\n\ngoog.require('goog.debug');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventType');\ngoog.require('goog.reflect');\ngoog.require('goog.userAgent');\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * The content of this object will not be initialized if no event object is\n * provided. If this is the case, init() needs to be invoked separately.\n * @param {Event=} opt_e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\n 'use strict';\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\n\n /**\n * Target that fired the event.\n * @override\n * @type {?Node}\n */\n this.target = null;\n\n /**\n * Node that had the listener attached.\n * @override\n * @type {?Node|undefined}\n */\n this.currentTarget = null;\n\n /**\n * For mouseover and mouseout events, the related object for the event.\n * @type {?Node}\n */\n this.relatedTarget = null;\n\n /**\n * X-coordinate relative to target.\n * @type {number}\n */\n this.offsetX = 0;\n\n /**\n * Y-coordinate relative to target.\n * @type {number}\n */\n this.offsetY = 0;\n\n /**\n * X-coordinate relative to the window.\n * @type {number}\n */\n this.clientX = 0;\n\n /**\n * Y-coordinate relative to the window.\n * @type {number}\n */\n this.clientY = 0;\n\n /**\n * X-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenX = 0;\n\n /**\n * Y-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenY = 0;\n\n /**\n * Which mouse button was pressed.\n * @type {number}\n */\n this.button = 0;\n\n /**\n * Key of key press.\n * @type {string}\n */\n this.key = '';\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.keyCode = 0;\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.charCode = 0;\n\n /**\n * Whether control was pressed at time of event.\n * @type {boolean}\n */\n this.ctrlKey = false;\n\n /**\n * Whether alt was pressed at time of event.\n * @type {boolean}\n */\n this.altKey = false;\n\n /**\n * Whether shift was pressed at time of event.\n * @type {boolean}\n */\n this.shiftKey = false;\n\n /**\n * Whether the meta key was pressed at time of event.\n * @type {boolean}\n */\n this.metaKey = false;\n\n /**\n * History state object, only set for PopState events where it's a copy of the\n * state object provided to pushState or replaceState.\n * @type {?Object}\n */\n this.state = null;\n\n /**\n * Whether the default platform modifier key was pressed at time of event.\n * (This is control for all platforms except Mac, where it's Meta.)\n * @type {boolean}\n */\n this.platformModifierKey = false;\n\n /**\n * @type {number}\n */\n this.pointerId = 0;\n\n /**\n * @type {string}\n */\n this.pointerType = '';\n\n /**\n * The browser event object.\n * @private {?Event}\n */\n this.event_ = null;\n\n if (opt_e) {\n this.init(opt_e, opt_currentTarget);\n }\n};\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\n\n/**\n * @define {boolean} If true, use the layerX and layerY properties of a native\n * browser event over the offsetX and offsetY properties, which cause expensive\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\n * as usual.\n */\ngoog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY =\n goog.define('goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY', false);\n\n\n/**\n * Normalized button constants for the mouse.\n * @enum {number}\n */\ngoog.events.BrowserEvent.MouseButton = {\n LEFT: 0,\n MIDDLE: 1,\n RIGHT: 2\n};\n\n\n/**\n * Normalized pointer type constants for pointer events.\n * @enum {string}\n */\ngoog.events.BrowserEvent.PointerType = {\n MOUSE: 'mouse',\n PEN: 'pen',\n TOUCH: 'touch'\n};\n\n\n/**\n * Static data for mapping mouse buttons.\n * @type {!Array<number>}\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\n */\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\n 1, // LEFT\n 4, // MIDDLE\n 2 // RIGHT\n]);\n\n\n/**\n * Static data for mapping mouse buttons.\n * @const {!Array<number>}\n */\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\n\n\n/**\n * Static data for mapping MSPointerEvent types to PointerEvent types.\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\n */\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\n 3: goog.events.BrowserEvent.PointerType.PEN,\n 4: goog.events.BrowserEvent.PointerType.MOUSE\n});\n\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * @param {Event} e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n */\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\n 'use strict';\n var type = this.type = e.type;\n\n /**\n * On touch devices use the first \"changed touch\" as the relevant touch.\n * @type {?Touch}\n */\n var relevantTouch =\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\n\n // TODO(nicksantos): Change this.target to type EventTarget.\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\n\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\n\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\n if (relatedTarget) {\n // There's a bug in FireFox where sometimes, relatedTarget will be a\n // chrome element, and accessing any property of it will get a permission\n // denied exception. See:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\n if (goog.userAgent.GECKO) {\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\n relatedTarget = null;\n }\n }\n } else if (type == goog.events.EventType.MOUSEOVER) {\n relatedTarget = e.fromElement;\n } else if (type == goog.events.EventType.MOUSEOUT) {\n relatedTarget = e.toElement;\n }\n\n this.relatedTarget = relatedTarget;\n\n if (relevantTouch) {\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\n relevantTouch.pageX;\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\n relevantTouch.pageY;\n this.screenX = relevantTouch.screenX || 0;\n this.screenY = relevantTouch.screenY || 0;\n } else {\n if (goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY) {\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\n } else {\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\n // http://code.google.com/p/chromium/issues/detail?id=101733\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\n e.offsetX :\n e.layerX;\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\n e.offsetY :\n e.layerY;\n }\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\n this.screenX = e.screenX || 0;\n this.screenY = e.screenY || 0;\n }\n\n this.button = e.button;\n\n this.keyCode = e.keyCode || 0;\n this.key = e.key || '';\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\n this.ctrlKey = e.ctrlKey;\n this.altKey = e.altKey;\n this.shiftKey = e.shiftKey;\n this.metaKey = e.metaKey;\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\n this.pointerId = e.pointerId || 0;\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\n this.state = e.state;\n this.event_ = e;\n if (e.defaultPrevented) {\n // Sync native event state to internal state via super class, where default\n // prevention is implemented and managed.\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n }\n};\n\n\n/**\n * Tests to see which button was pressed during the event. This is really only\n * useful in IE and Gecko browsers. And in IE, it's only useful for\n * mousedown/mouseup events, because click only fires for the left mouse button.\n *\n * Safari 2 only reports the left button being clicked, and uses the value '1'\n * instead of 0. Opera only reports a mousedown event for the middle button, and\n * no mouse events for the right button. Opera has default behavior for left and\n * middle click that can only be overridden via a configuration setting.\n *\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\n *\n * @param {goog.events.BrowserEvent.MouseButton} button The button\n * to test for.\n * @return {boolean} True if button was pressed.\n */\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\n 'use strict';\n return this.event_.button == button;\n};\n\n\n/**\n * Whether this has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @return {boolean} The result.\n */\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\n 'use strict';\n // Ctrl+click should never behave like a left-click on mac, regardless of\n // whether or not the browser will actually ever emit such an event. If\n // we see it, treat it like right-click always.\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\n !(goog.userAgent.MAC && this.ctrlKey);\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\n if (this.event_.stopPropagation) {\n this.event_.stopPropagation();\n } else {\n this.event_.cancelBubble = true;\n }\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n var be = this.event_;\n if (!be.preventDefault) {\n be.returnValue = false;\n } else {\n be.preventDefault();\n }\n};\n\n\n/**\n * @return {Event} The underlying browser event object.\n */\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\n 'use strict';\n return this.event_;\n};\n\n\n/**\n * Extracts the pointer type from the given event.\n * @param {!Event} e\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\n * @private\n */\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\n 'use strict';\n if (typeof (e.pointerType) === 'string') {\n return e.pointerType;\n }\n // IE10 uses integer codes for pointer type.\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Event Types.\n */\n\n\ngoog.provide('goog.events.EventType');\ngoog.provide('goog.events.EventTypeHelpers');\ngoog.provide('goog.events.MouseAsMouseEventType');\ngoog.provide('goog.events.MouseEvents');\ngoog.provide('goog.events.PointerAsMouseEventType');\ngoog.provide('goog.events.PointerAsTouchEventType');\ngoog.provide('goog.events.PointerFallbackEventType');\ngoog.provide('goog.events.PointerTouchFallbackEventType');\n\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.userAgent');\n\n\n/**\n * Returns a prefixed event name for the current browser.\n * @param {string} eventName The name of the event.\n * @return {string} The prefixed event name.\n * @private\n */\ngoog.events.EventTypeHelpers.getVendorPrefixedName_ = function(eventName) {\n 'use strict';\n return goog.userAgent.WEBKIT ? 'webkit' + eventName : eventName.toLowerCase();\n};\n\n\n/**\n * Constants for event names.\n * @enum {string}\n */\ngoog.events.EventType = {\n // Mouse events\n CLICK: 'click',\n RIGHTCLICK: 'rightclick',\n DBLCLICK: 'dblclick',\n AUXCLICK: 'auxclick',\n MOUSEDOWN: 'mousedown',\n MOUSEUP: 'mouseup',\n MOUSEOVER: 'mouseover',\n MOUSEOUT: 'mouseout',\n MOUSEMOVE: 'mousemove',\n MOUSEENTER: 'mouseenter',\n MOUSELEAVE: 'mouseleave',\n\n // Non-existent event; will never fire. This exists as a mouse counterpart to\n // POINTERCANCEL.\n MOUSECANCEL: 'mousecancel',\n\n // Selection events.\n // https://www.w3.org/TR/selection-api/\n SELECTIONCHANGE: 'selectionchange',\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\n\n // Wheel events\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n WHEEL: 'wheel',\n\n // Key events\n KEYPRESS: 'keypress',\n KEYDOWN: 'keydown',\n KEYUP: 'keyup',\n\n // Focus\n BLUR: 'blur',\n FOCUS: 'focus',\n DEACTIVATE: 'deactivate', // IE only\n FOCUSIN: 'focusin',\n FOCUSOUT: 'focusout',\n\n // Forms\n CHANGE: 'change',\n RESET: 'reset',\n SELECT: 'select',\n SUBMIT: 'submit',\n INPUT: 'input',\n PROPERTYCHANGE: 'propertychange', // IE only\n\n // Drag and drop\n DRAGSTART: 'dragstart',\n DRAG: 'drag',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DRAGLEAVE: 'dragleave',\n DROP: 'drop',\n DRAGEND: 'dragend',\n\n // Touch events\n // Note that other touch events exist, but we should follow the W3C list here.\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\n TOUCHSTART: 'touchstart',\n TOUCHMOVE: 'touchmove',\n TOUCHEND: 'touchend',\n TOUCHCANCEL: 'touchcancel',\n\n // Misc\n BEFOREUNLOAD: 'beforeunload',\n CONSOLEMESSAGE: 'consolemessage',\n CONTEXTMENU: 'contextmenu',\n DEVICECHANGE: 'devicechange',\n DEVICEMOTION: 'devicemotion',\n DEVICEORIENTATION: 'deviceorientation',\n DOMCONTENTLOADED: 'DOMContentLoaded',\n ERROR: 'error',\n HELP: 'help',\n LOAD: 'load',\n LOSECAPTURE: 'losecapture',\n ORIENTATIONCHANGE: 'orientationchange',\n READYSTATECHANGE: 'readystatechange',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n UNLOAD: 'unload',\n\n // Media events\n CANPLAY: 'canplay',\n CANPLAYTHROUGH: 'canplaythrough',\n DURATIONCHANGE: 'durationchange',\n EMPTIED: 'emptied',\n ENDED: 'ended',\n LOADEDDATA: 'loadeddata',\n LOADEDMETADATA: 'loadedmetadata',\n PAUSE: 'pause',\n PLAY: 'play',\n PLAYING: 'playing',\n PROGRESS: 'progress',\n RATECHANGE: 'ratechange',\n SEEKED: 'seeked',\n SEEKING: 'seeking',\n STALLED: 'stalled',\n SUSPEND: 'suspend',\n TIMEUPDATE: 'timeupdate',\n VOLUMECHANGE: 'volumechange',\n WAITING: 'waiting',\n\n // Media Source Extensions events\n // https://www.w3.org/TR/media-source/#mediasource-events\n SOURCEOPEN: 'sourceopen',\n SOURCEENDED: 'sourceended',\n SOURCECLOSED: 'sourceclosed',\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\n ABORT: 'abort',\n UPDATE: 'update',\n UPDATESTART: 'updatestart',\n UPDATEEND: 'updateend',\n\n // HTML 5 History events\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\n HASHCHANGE: 'hashchange',\n PAGEHIDE: 'pagehide',\n PAGESHOW: 'pageshow',\n POPSTATE: 'popstate',\n\n // Copy and Paste\n // Support is limited. Make sure it works on your favorite browser\n // before using.\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\n COPY: 'copy',\n PASTE: 'paste',\n CUT: 'cut',\n BEFORECOPY: 'beforecopy',\n BEFORECUT: 'beforecut',\n BEFOREPASTE: 'beforepaste',\n\n // HTML5 online/offline events.\n // http://www.w3.org/TR/offline-webapps/#related\n ONLINE: 'online',\n OFFLINE: 'offline',\n\n // HTML 5 worker events\n MESSAGE: 'message',\n CONNECT: 'connect',\n\n // Service Worker Events - ServiceWorkerGlobalScope context\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\n // Note: message event defined in worker events section\n INSTALL: 'install',\n ACTIVATE: 'activate',\n FETCH: 'fetch',\n FOREIGNFETCH: 'foreignfetch',\n MESSAGEERROR: 'messageerror',\n\n // Service Worker Events - Document context\n // See https://w3c.github.io/ServiceWorker/#document-context-events\n STATECHANGE: 'statechange',\n UPDATEFOUND: 'updatefound',\n CONTROLLERCHANGE: 'controllerchange',\n\n // CSS animation events.\n ANIMATIONSTART:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('AnimationStart'),\n ANIMATIONEND:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('AnimationEnd'),\n ANIMATIONITERATION:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('AnimationIteration'),\n\n // CSS transition events. Based on the browser support described at:\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\n TRANSITIONEND:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('TransitionEnd'),\n\n // W3C Pointer Events\n // http://www.w3.org/TR/pointerevents/\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTERCANCEL: 'pointercancel',\n POINTERMOVE: 'pointermove',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n GOTPOINTERCAPTURE: 'gotpointercapture',\n LOSTPOINTERCAPTURE: 'lostpointercapture',\n\n // IE specific events.\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n // Note: these events will be supplanted in IE11.\n MSGESTURECHANGE: 'MSGestureChange',\n MSGESTUREEND: 'MSGestureEnd',\n MSGESTUREHOLD: 'MSGestureHold',\n MSGESTURESTART: 'MSGestureStart',\n MSGESTURETAP: 'MSGestureTap',\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\n MSINERTIASTART: 'MSInertiaStart',\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\n MSPOINTERCANCEL: 'MSPointerCancel',\n MSPOINTERDOWN: 'MSPointerDown',\n MSPOINTERENTER: 'MSPointerEnter',\n MSPOINTERHOVER: 'MSPointerHover',\n MSPOINTERLEAVE: 'MSPointerLeave',\n MSPOINTERMOVE: 'MSPointerMove',\n MSPOINTEROUT: 'MSPointerOut',\n MSPOINTEROVER: 'MSPointerOver',\n MSPOINTERUP: 'MSPointerUp',\n\n // Native IMEs/input tools events.\n TEXT: 'text',\n // The textInput event is supported in IE9+, but only in lower case. All other\n // browsers use the camel-case event name.\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\n COMPOSITIONSTART: 'compositionstart',\n COMPOSITIONUPDATE: 'compositionupdate',\n COMPOSITIONEND: 'compositionend',\n\n // The beforeinput event is initially only supported in Safari. See\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\n // implementation tracking.\n BEFOREINPUT: 'beforeinput',\n\n // Webview tag events\n // See https://developer.chrome.com/apps/tags/webview\n EXIT: 'exit',\n LOADABORT: 'loadabort',\n LOADCOMMIT: 'loadcommit',\n LOADREDIRECT: 'loadredirect',\n LOADSTART: 'loadstart',\n LOADSTOP: 'loadstop',\n RESPONSIVE: 'responsive',\n SIZECHANGED: 'sizechanged',\n UNRESPONSIVE: 'unresponsive',\n\n // HTML5 Page Visibility API. See details at\n // `goog.labs.dom.PageVisibilityMonitor`.\n VISIBILITYCHANGE: 'visibilitychange',\n\n // LocalStorage event.\n STORAGE: 'storage',\n\n // DOM Level 2 mutation events (deprecated).\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\n DOMNODEINSERTED: 'DOMNodeInserted',\n DOMNODEREMOVED: 'DOMNodeRemoved',\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\n DOMATTRMODIFIED: 'DOMAttrModified',\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\n\n // Print events.\n BEFOREPRINT: 'beforeprint',\n AFTERPRINT: 'afterprint',\n\n // Web app manifest events.\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\n APPINSTALLED: 'appinstalled'\n};\n\n\n/**\n * Returns one of the given pointer fallback event names in order of preference:\n * 1. pointerEventName\n * 2. msPointerEventName\n * 3. fallbackEventName\n * @param {string} pointerEventName\n * @param {string} msPointerEventName\n * @param {string} fallbackEventName\n * @return {string} The supported pointer or fallback (mouse or touch) event\n * name.\n * @private\n */\ngoog.events.EventTypeHelpers.getPointerFallbackEventName_ = function(\n pointerEventName, msPointerEventName, fallbackEventName) {\n 'use strict';\n if (goog.events.BrowserFeature.POINTER_EVENTS) {\n return pointerEventName;\n }\n if (goog.events.BrowserFeature.MSPOINTER_EVENTS) {\n return msPointerEventName;\n }\n return fallbackEventName;\n};\n\n\n/**\n * Constants for pointer event names that fall back to corresponding mouse event\n * names on unsupported platforms. These are intended to be drop-in replacements\n * for corresponding values in `goog.events.EventType`.\n * @enum {string}\n */\ngoog.events.PointerFallbackEventType = {\n POINTERDOWN: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\n goog.events.EventType.MOUSEDOWN),\n POINTERUP: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\n goog.events.EventType.MOUSEUP),\n POINTERCANCEL: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERCANCEL,\n goog.events.EventType.MSPOINTERCANCEL,\n // When falling back to mouse events, there is no MOUSECANCEL equivalent\n // of POINTERCANCEL. In this case POINTERUP already falls back to MOUSEUP\n // which represents both UP and CANCEL. POINTERCANCEL does not fall back\n // to MOUSEUP to prevent listening twice on the same event.\n goog.events.EventType.MOUSECANCEL),\n POINTERMOVE: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\n goog.events.EventType.MOUSEMOVE),\n POINTEROVER: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTEROVER, goog.events.EventType.MSPOINTEROVER,\n goog.events.EventType.MOUSEOVER),\n POINTEROUT: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTEROUT, goog.events.EventType.MSPOINTEROUT,\n goog.events.EventType.MOUSEOUT),\n POINTERENTER: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERENTER, goog.events.EventType.MSPOINTERENTER,\n goog.events.EventType.MOUSEENTER),\n POINTERLEAVE: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERLEAVE, goog.events.EventType.MSPOINTERLEAVE,\n goog.events.EventType.MOUSELEAVE)\n};\n\n\n/**\n * Constants for pointer event names that fall back to corresponding touch event\n * names on unsupported platforms. These are intended to be drop-in replacements\n * for corresponding values in `goog.events.EventType`.\n * @enum {string}\n */\ngoog.events.PointerTouchFallbackEventType = {\n POINTERDOWN: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\n goog.events.EventType.TOUCHSTART),\n POINTERUP: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\n goog.events.EventType.TOUCHEND),\n POINTERCANCEL: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERCANCEL,\n goog.events.EventType.MSPOINTERCANCEL, goog.events.EventType.TOUCHCANCEL),\n POINTERMOVE: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\n goog.events.EventType.TOUCHMOVE)\n};\n\n\n/**\n * Mapping of mouse event names to underlying browser event names.\n * @typedef {{\n * MOUSEDOWN: string,\n * MOUSEUP: string,\n * MOUSECANCEL:string,\n * MOUSEMOVE:string,\n * MOUSEOVER:string,\n * MOUSEOUT:string,\n * MOUSEENTER:string,\n * MOUSELEAVE: string,\n * }}\n */\ngoog.events.MouseEvents;\n\n\n/**\n * An alias for `goog.events.EventType.MOUSE*` event types that is overridden by\n * corresponding `POINTER*` event types.\n * @const {!goog.events.MouseEvents}\n */\ngoog.events.PointerAsMouseEventType = {\n MOUSEDOWN: goog.events.PointerFallbackEventType.POINTERDOWN,\n MOUSEUP: goog.events.PointerFallbackEventType.POINTERUP,\n MOUSECANCEL: goog.events.PointerFallbackEventType.POINTERCANCEL,\n MOUSEMOVE: goog.events.PointerFallbackEventType.POINTERMOVE,\n MOUSEOVER: goog.events.PointerFallbackEventType.POINTEROVER,\n MOUSEOUT: goog.events.PointerFallbackEventType.POINTEROUT,\n MOUSEENTER: goog.events.PointerFallbackEventType.POINTERENTER,\n MOUSELEAVE: goog.events.PointerFallbackEventType.POINTERLEAVE\n};\n\n\n/**\n * An alias for `goog.events.EventType.MOUSE*` event types that continue to use\n * mouse events.\n * @const {!goog.events.MouseEvents}\n */\ngoog.events.MouseAsMouseEventType = {\n MOUSEDOWN: goog.events.EventType.MOUSEDOWN,\n MOUSEUP: goog.events.EventType.MOUSEUP,\n MOUSECANCEL: goog.events.EventType.MOUSECANCEL,\n MOUSEMOVE: goog.events.EventType.MOUSEMOVE,\n MOUSEOVER: goog.events.EventType.MOUSEOVER,\n MOUSEOUT: goog.events.EventType.MOUSEOUT,\n MOUSEENTER: goog.events.EventType.MOUSEENTER,\n MOUSELEAVE: goog.events.EventType.MOUSELEAVE\n};\n\n\n/**\n * An alias for `goog.events.EventType.TOUCH*` event types that is overridden by\n * corresponding `POINTER*` event types.\n * @enum {string}\n */\ngoog.events.PointerAsTouchEventType = {\n TOUCHCANCEL: goog.events.PointerTouchFallbackEventType.POINTERCANCEL,\n TOUCHEND: goog.events.PointerTouchFallbackEventType.POINTERUP,\n TOUCHMOVE: goog.events.PointerTouchFallbackEventType.POINTERMOVE,\n TOUCHSTART: goog.events.PointerTouchFallbackEventType.POINTERDOWN\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface for a listenable JavaScript object.\n */\n\ngoog.provide('goog.events.Listenable');\n\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n/**\n * A listenable interface. A listenable is an object with the ability\n * to dispatch/broadcast events to \"event listeners\" registered via\n * listen/listenOnce.\n *\n * The interface allows for an event propagation mechanism similar\n * to one offered by native browser event targets, such as\n * capture/bubble mechanism, stopping propagation, and preventing\n * default actions. Capture/bubble mechanism depends on the ancestor\n * tree constructed via `#getParentEventTarget`; this tree\n * must be directed acyclic graph. The meaning of default action(s)\n * in preventDefault is specific to a particular use case.\n *\n * Implementations that do not support capture/bubble or can not have\n * a parent listenable can simply not implement any ability to set the\n * parent listenable (and have `#getParentEventTarget` return\n * null).\n *\n * Implementation of this class can be used with or independently from\n * goog.events.\n *\n * Implementation must call `#addImplementation(implClass)`.\n *\n * @interface\n * @see goog.events\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\n */\ngoog.events.Listenable = function() {};\n\n\n/**\n * An expando property to indicate that an object implements\n * goog.events.Listenable.\n *\n * See addImplementation/isImplementedBy.\n *\n * @type {string}\n * @const\n */\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * Marks a given class (constructor) as an implementation of\n * Listenable, so that we can query that fact at runtime. The class\n * must have already implemented the interface.\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\n * The corresponding class must have already implemented the interface.\n */\ngoog.events.Listenable.addImplementation = function(cls) {\n 'use strict';\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\n};\n\n\n/**\n * @param {?Object} obj The object to check.\n * @return {boolean} Whether a given instance implements Listenable. The\n * class/superclass of the instance must call addImplementation.\n */\ngoog.events.Listenable.isImplementedBy = function(obj) {\n 'use strict';\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Adds an event listener that is removed automatically after the\n * listener fired once.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() or listenOnce().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.Listenable.prototype.unlistenByKey = function(key) {};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n */\ngoog.events.Listenable.prototype.dispatchEvent = function(e) {};\n\n\n/**\n * Removes all listeners from this listenable. If type is specified,\n * it will only remove listeners of the particular type. otherwise all\n * registered listeners will be removed.\n *\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.Listenable.prototype.removeAllListeners = function(opt_type) {};\n\n\n/**\n * Returns the parent of this event target to use for capture/bubble\n * mechanism.\n *\n * NOTE(chrishenry): The name reflects the original implementation of\n * custom event target (`goog.events.EventTarget`). We decided\n * that changing the name is not worth it.\n *\n * @return {?goog.events.Listenable} The parent EventTarget or null if\n * there is no parent.\n */\ngoog.events.Listenable.prototype.getParentEventTarget = function() {};\n\n\n/**\n * Fires all registered listeners in this listenable for the given\n * type and capture mode, passing them the given eventObject. This\n * does not perform actual capture/bubble. Only implementors of the\n * interface should be using this.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.fireListeners = function(\n type, capture, eventObject) {};\n\n\n/**\n * Gets all listeners in this listenable for the given type and\n * capture mode.\n *\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListeners = function(type, capture) {};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {};\n\n\n/**\n * Whether there is any active listeners matching the specified\n * signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.hasListener = function(\n opt_type, opt_capture) {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface that describes a single registered listener.\n */\ngoog.provide('goog.events.ListenableKey');\n\ngoog.requireType('goog.events.Listenable');\n\n\n/**\n * An interface that describes a single registered listener.\n * @interface\n */\ngoog.events.ListenableKey = function() {};\n\n\n/**\n * Counter used to create a unique key\n * @type {number}\n * @private\n */\ngoog.events.ListenableKey.counter_ = 0;\n\n\n/**\n * Reserves a key to be used for ListenableKey#key field.\n * @return {number} A number to be used to fill ListenableKey#key\n * field.\n */\ngoog.events.ListenableKey.reserveKey = function() {\n 'use strict';\n return ++goog.events.ListenableKey.counter_;\n};\n\n\n/**\n * The source event target.\n * @type {?Object|?goog.events.Listenable}\n */\ngoog.events.ListenableKey.prototype.src;\n\n\n/**\n * The event type the listener is listening to.\n * @type {string}\n */\ngoog.events.ListenableKey.prototype.type;\n\n\n/**\n * The listener function.\n * @type {function(?):?|{handleEvent:function(?):?}|null}\n */\ngoog.events.ListenableKey.prototype.listener;\n\n\n/**\n * Whether the listener works on capture phase.\n * @type {boolean}\n */\ngoog.events.ListenableKey.prototype.capture;\n\n\n/**\n * The 'this' object for the listener function's scope.\n * @type {?Object|undefined}\n */\ngoog.events.ListenableKey.prototype.handler;\n\n\n/**\n * A globally unique number to identify the key.\n * @type {number}\n */\ngoog.events.ListenableKey.prototype.key;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Listener object.\n * @see ../demos/events.html\n */\n\ngoog.provide('goog.events.Listener');\n\ngoog.require('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listenable');\n\n\n\n/**\n * Simple class that stores information about a listener\n * @param {function(?):?} listener Callback function.\n * @param {Function} proxy Wrapper for the listener that patches the event.\n * @param {EventTarget|goog.events.Listenable} src Source object for\n * the event.\n * @param {string} type Event type.\n * @param {boolean} capture Whether in capture or bubble phase.\n * @param {Object=} opt_handler Object in whose context to execute the callback.\n * @implements {goog.events.ListenableKey}\n * @constructor\n */\ngoog.events.Listener = function(\n listener, proxy, src, type, capture, opt_handler) {\n 'use strict';\n if (goog.events.Listener.ENABLE_MONITORING) {\n this.creationStack = new Error().stack;\n }\n\n /** @override */\n this.listener = listener;\n\n /**\n * A wrapper over the original listener. This is used solely to\n * handle native browser events (it is used to simulate the capture\n * phase and to patch the event object).\n * @type {Function}\n */\n this.proxy = proxy;\n\n /**\n * Object or node that callback is listening to\n * @type {EventTarget|goog.events.Listenable}\n */\n this.src = src;\n\n /**\n * The event type.\n * @const {string}\n */\n this.type = type;\n\n /**\n * Whether the listener is being called in the capture or bubble phase\n * @const {boolean}\n */\n this.capture = !!capture;\n\n /**\n * Optional object whose context to execute the listener in\n * @type {Object|undefined}\n */\n this.handler = opt_handler;\n\n /**\n * The key of the listener.\n * @const {number}\n * @override\n */\n this.key = goog.events.ListenableKey.reserveKey();\n\n /**\n * Whether to remove the listener after it has been called.\n * @type {boolean}\n */\n this.callOnce = false;\n\n /**\n * Whether the listener has been removed.\n * @type {boolean}\n */\n this.removed = false;\n};\n\n\n/**\n * @define {boolean} Whether to enable the monitoring of the\n * goog.events.Listener instances. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.events.Listener.ENABLE_MONITORING =\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\n\n\n/**\n * If monitoring the goog.events.Listener instances is enabled, stores the\n * creation stack trace of the Disposable instance.\n * @type {string}\n */\ngoog.events.Listener.prototype.creationStack;\n\n\n/**\n * Marks this listener as removed. This also remove references held by\n * this listener object (such as listener and event source).\n */\ngoog.events.Listener.prototype.markAsRemoved = function() {\n 'use strict';\n this.removed = true;\n this.listener = null;\n this.proxy = null;\n this.src = null;\n this.handler = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A map of listeners that provides utility functions to\n * deal with listeners on an event target. Used by\n * `goog.events.EventTarget`.\n *\n * WARNING: Do not use this class from outside goog.events package.\n *\n */\n\ngoog.provide('goog.events.ListenerMap');\n\ngoog.require('goog.array');\ngoog.require('goog.events.Listener');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.Listenable');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * Creates a new listener map.\n * @param {EventTarget|goog.events.Listenable} src The src object.\n * @constructor\n * @final\n */\ngoog.events.ListenerMap = function(src) {\n 'use strict';\n /** @type {EventTarget|goog.events.Listenable} */\n this.src = src;\n\n /**\n * Maps of event type to an array of listeners.\n * @type {!Object<string, !Array<!goog.events.Listener>>}\n */\n this.listeners = {};\n\n /**\n * The count of types in this map that have registered listeners.\n * @private {number}\n */\n this.typeCount_ = 0;\n};\n\n\n/**\n * @return {number} The count of event types in this map that actually\n * have registered listeners.\n */\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\n 'use strict';\n return this.typeCount_;\n};\n\n\n/**\n * @return {number} Total number of registered listeners.\n */\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var type in this.listeners) {\n count += this.listeners[type].length;\n }\n return count;\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n */\ngoog.events.ListenerMap.prototype.add = function(\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n var listenerArray = this.listeners[typeStr];\n if (!listenerArray) {\n listenerArray = this.listeners[typeStr] = [];\n this.typeCount_++;\n }\n\n var listenerObj;\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n listenerObj = listenerArray[index];\n if (!callOnce) {\n // Ensure that, if there is an existing callOnce listener, it is no\n // longer a callOnce listener.\n listenerObj.callOnce = false;\n }\n } else {\n listenerObj = new goog.events.Listener(\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\n listenerObj.callOnce = callOnce;\n listenerArray.push(listenerObj);\n }\n return listenerObj;\n};\n\n\n/**\n * Removes a matching listener.\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.ListenerMap.prototype.remove = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n if (!(typeStr in this.listeners)) {\n return false;\n }\n\n var listenerArray = this.listeners[typeStr];\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n var listenerObj = listenerArray[index];\n listenerObj.markAsRemoved();\n goog.array.removeAt(listenerArray, index);\n if (listenerArray.length == 0) {\n delete this.listeners[typeStr];\n this.typeCount_--;\n }\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes the given listener object.\n * @param {!goog.events.ListenableKey} listener The listener to remove.\n * @return {boolean} Whether the listener is removed.\n */\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\n 'use strict';\n var type = listener.type;\n if (!(type in this.listeners)) {\n return false;\n }\n\n var removed = goog.array.remove(this.listeners[type], listener);\n if (removed) {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n if (this.listeners[type].length == 0) {\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return removed;\n};\n\n\n/**\n * Removes all listeners from this map. If opt_type is provided, only\n * listeners that match the given type are removed.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * @return {number} Number of listeners removed.\n */\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\n 'use strict';\n var typeStr = opt_type && opt_type.toString();\n var count = 0;\n for (var type in this.listeners) {\n if (!typeStr || type == typeStr) {\n var listenerArray = this.listeners[type];\n for (var i = 0; i < listenerArray.length; i++) {\n ++count;\n listenerArray[i].markAsRemoved();\n }\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return count;\n};\n\n\n/**\n * Gets all listeners that match the given type and capture mode. The\n * returned array is a copy (but the listener objects are not).\n * @param {string|!goog.events.EventId} type The type of the listeners\n * to retrieve.\n * @param {boolean} capture The capture mode of the listeners to retrieve.\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\n * listeners.\n */\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var rv = [];\n if (listenerArray) {\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (listenerObj.capture == capture) {\n rv.push(listenerObj);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId} type The type of the listener\n * to retrieve.\n * @param {!Function} listener The listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n */\ngoog.events.ListenerMap.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var i = -1;\n if (listenerArray) {\n i = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, capture, opt_listenerScope);\n }\n return i > -1 ? listenerArray[i] : null;\n};\n\n\n/**\n * Whether there is a matching listener. If either the type or capture\n * parameters are unspecified, the function will match on the\n * remaining criteria.\n *\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\n * @param {boolean=} opt_capture The capture mode of the listener.\n * @return {boolean} Whether there is an active listener matching\n * the requested type and/or capture phase.\n */\ngoog.events.ListenerMap.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var hasType = (opt_type !== undefined);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = (opt_capture !== undefined);\n\n return goog.object.some(this.listeners, function(listenerArray, type) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n if ((!hasType || listenerArray[i].type == typeStr) &&\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\n return true;\n }\n }\n\n return false;\n });\n};\n\n\n/**\n * Finds the index of a matching goog.events.Listener in the given\n * listenerArray.\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\n * @param {!Function} listener The listener function.\n * @param {boolean=} opt_useCapture The capture flag for the listener.\n * @param {Object=} opt_listenerScope The listener scope.\n * @return {number} The index of the matching listener within the\n * listenerArray.\n * @private\n */\ngoog.events.ListenerMap.findListenerIndex_ = function(\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (!listenerObj.removed && listenerObj.listener == listener &&\n listenerObj.capture == !!opt_useCapture &&\n listenerObj.handler == opt_listenerScope) {\n return i;\n }\n }\n return -1;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating objects/maps/hashes.\n */\ngoog.module('goog.object');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls a function for each element in an object/map/hash.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):?} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and the return value is ignored.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {void}\n * @template T,K,V\n */\nfunction forEach(obj, f, opt_obj) {\n for (const key in obj) {\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If that call returns\n * true, adds the element to a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean. If the return value is true the\n * element is added to the result object. If it is false the element is not\n * included.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,V>} a new object in which only elements that passed the\n * test are present.\n * @template T,K,V\n */\nfunction filter(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n res[key] = obj[key];\n }\n }\n return res;\n}\n\n/**\n * For every element in an object/map/hash calls a function and inserts the\n * result into a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):R} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and should return something. The result will be inserted into a\n * new object.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,R>} a new object with the results from f.\n * @template T,K,V,R\n */\nfunction map(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n return res;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If any\n * call returns true, returns true (without checking the rest). If\n * all calls return false, returns false.\n * @param {?Object<K,V>} obj The object to check.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} true if any element passes the test.\n * @template T,K,V\n */\nfunction some(obj, f, opt_obj) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If\n * all calls return true, returns true. If any call returns false, returns\n * false at this point and does not continue to check the remaining elements.\n * @param {?Object<K,V>} obj The object to check.\n * @param {?function(this:T,V,?,?Object<K,V>):boolean} f The function to call\n * for every element. This function takes 3 arguments (the value, the key\n * and the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} false if any element fails the test.\n * @template T,K,V\n */\nfunction every(obj, f, opt_obj) {\n for (const key in obj) {\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns the number of key-value pairs in the object map.\n * @param {?Object} obj The object for which to get the number of key-value\n * pairs.\n * @return {number} The number of key-value pairs in the object map.\n */\nfunction getCount(obj) {\n let rv = 0;\n for (const key in obj) {\n rv++;\n }\n return rv;\n}\n\n/**\n * Returns one key from the object map, if any exists.\n * For map literals the returned key will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object} obj The object to pick a key from.\n * @return {string|undefined} The key or undefined if the object is empty.\n */\nfunction getAnyKey(obj) {\n for (const key in obj) {\n return key;\n }\n}\n\n/**\n * Returns one value from the object map, if any exists.\n * For map literals the returned value will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object<K,V>} obj The object to pick a value from.\n * @return {V|undefined} The value or undefined if the object is empty.\n * @template K,V\n */\nfunction getAnyValue(obj) {\n for (const key in obj) {\n return obj[key];\n }\n}\n\n/**\n * Whether the object/hash/map contains the given object as a value.\n * An alias for containsValue(obj, val).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The object for which to check.\n * @return {boolean} true if val is present.\n * @template K,V\n */\nfunction contains(obj, val) {\n return containsValue(obj, val);\n}\n\n/**\n * Returns the values of the object/map/hash.\n * @param {?Object<K,V>} obj The object from which to get the values.\n * @return {!Array<V>} The values in the object/map/hash.\n * @template K,V\n */\nfunction getValues(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = obj[key];\n }\n return res;\n}\n\n/**\n * Returns the keys of the object/map/hash.\n * @param {?Object} obj The object from which to get the keys.\n * @return {!Array<string>} Array of property keys.\n */\nfunction getKeys(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = key;\n }\n return res;\n}\n\n/**\n * Get a value from an object multiple levels deep. This is useful for\n * pulling values from deeply nested objects, such as JSON responses.\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\n * @param {?Object} obj An object to get the value from. Can be array-like.\n * @param {...(string|number|!IArrayLike<number|string>)} var_args A number of\n * keys (as strings, or numbers, for array-like objects). Can also be\n * specified as a single array of keys.\n * @return {*} The resulting value. If, at any point, the value for a key in the\n * current object is null or undefined, returns undefined.\n */\nfunction getValueByKeys(obj, var_args) {\n const isArrayLike = goog.isArrayLike(var_args);\n const keys = isArrayLike ?\n /** @type {!IArrayLike<number|string>} */ (var_args) :\n arguments;\n\n // Start with the 2nd parameter for the variable parameters syntax.\n for (let i = isArrayLike ? 0 : 1; i < keys.length; i++) {\n if (obj == null) return undefined;\n obj = obj[keys[i]];\n }\n\n return obj;\n}\n\n/**\n * Whether the object/map/hash contains the given key.\n * @param {?Object} obj The object in which to look for key.\n * @param {?} key The key for which to check.\n * @return {boolean} true If the map contains the key.\n */\nfunction containsKey(obj, key) {\n return obj !== null && key in obj;\n}\n\n/**\n * Whether the object/map/hash contains the given value. This is O(n).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The value for which to check.\n * @return {boolean} true If the map contains the value.\n * @template K,V\n */\nfunction containsValue(obj, val) {\n for (const key in obj) {\n if (obj[key] == val) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its key.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {string|undefined} The key of an element for which the function\n * returns true or undefined if no such element is found.\n * @template T,K,V\n */\nfunction findKey(obj, f, thisObj = undefined) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (thisObj), obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its value.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {V} The value of an element for which the function returns true or\n * undefined if no such element is found.\n * @template T,K,V\n */\nfunction findValue(obj, f, thisObj = undefined) {\n const key = findKey(obj, f, thisObj);\n return key && obj[key];\n}\n\n/**\n * Whether the object/map/hash is empty.\n * @param {?Object} obj The object to test.\n * @return {boolean} true if obj is empty.\n */\nfunction isEmpty(obj) {\n for (const key in obj) {\n return false;\n }\n return true;\n}\n\n/**\n * Removes all key value pairs from the object/map/hash.\n * @param {?Object} obj The object to clear.\n * @return {void}\n */\nfunction clear(obj) {\n for (const i in obj) {\n delete obj[i];\n }\n}\n\n/**\n * Removes a key-value pair based on the key.\n * @param {?Object} obj The object from which to remove the key.\n * @param {?} key The key to remove.\n * @return {boolean} Whether an element was removed.\n */\nfunction remove(obj, key) {\n let rv;\n if (rv = key in /** @type {!Object} */ (obj)) {\n delete obj[key];\n }\n return rv;\n}\n\n/**\n * Adds a key-value pair to the object. Throws an exception if the key is\n * already in use. Use set if you want to change an existing pair.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} val The value to add.\n * @return {void}\n * @template K,V\n */\nfunction add(obj, key, val) {\n if (obj !== null && key in obj) {\n throw new Error(`The object already contains the key \"${key}\"`);\n }\n set(obj, key, val);\n}\n\n/**\n * Returns the value for the given key.\n * @param {?Object<K,V>} obj The object from which to get the value.\n * @param {string} key The key for which to get the value.\n * @param {R=} val The value to return if no item is found for the given key\n * (default is undefined).\n * @return {V|R|undefined} The value for the given key.\n * @template K,V,R\n */\nfunction get(obj, key, val = undefined) {\n if (obj !== null && key in obj) {\n return obj[key];\n }\n return val;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add.\n * @template K,V\n * @return {void}\n */\nfunction set(obj, key, value) {\n obj[key] = value;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setIfUndefined(obj, key, value) {\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\n}\n\n/**\n * Sets a key and value to an object if the key is not set. The value will be\n * the return value of the given function. If the key already exists, the\n * object will not be changed and the function will not be called (the function\n * will be lazily evaluated -- only called if necessary).\n * This function is particularly useful when used with an `Object` which is\n * acting as a cache.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {function():V} f The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setWithReturnValueIfNotSet(obj, key, f) {\n if (key in obj) {\n return obj[key];\n }\n\n const val = f();\n obj[key] = val;\n return val;\n}\n\n/**\n * Compares two objects for equality using === on the values.\n * @param {!Object<K,V>} a\n * @param {!Object<K,V>} b\n * @return {boolean}\n * @template K,V\n */\nfunction equals(a, b) {\n for (const k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns a shallow clone of the object.\n * @param {?Object<K,V>} obj Object to clone.\n * @return {!Object<K,V>} Clone of the input object.\n * @template K,V\n */\nfunction clone(obj) {\n const res = {};\n for (const key in obj) {\n res[key] = obj[key];\n }\n return res;\n}\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n * WARNINGS:\n * <code>unsafeClone</code> does not detect reference loops. Objects\n * that refer to themselves will cause infinite recursion.\n * <code>unsafeClone</code> is unaware of unique identifiers, and\n * copies UIDs created by <code>getUid</code> into cloned results.\n * @param {T} obj The value to clone.\n * @return {T} A clone of the input value.\n * @template T\n */\nfunction unsafeClone(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n if (typeof obj.clone === 'function') return obj.clone();\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n }\n const clone = Array.isArray(obj) ? [] :\n typeof ArrayBuffer === 'function' &&\n typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj) &&\n !(obj instanceof DataView) ?\n new obj.constructor(obj.length) :\n {};\n for (const key in obj) {\n clone[key] = unsafeClone(obj[key]);\n }\n return clone;\n}\n\n/**\n * Returns a new object in which all the keys and values are interchanged\n * (keys become values and values become keys). If multiple keys map to the\n * same value, the chosen transposed value is implementation-dependent.\n * @param {?Object} obj The object to transpose.\n * @return {!Object} The transposed object.\n */\nfunction transpose(obj) {\n const transposed = {};\n for (const key in obj) {\n transposed[obj[key]] = key;\n }\n return transposed;\n}\n\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n */\nconst PROTOTYPE_FIELDS = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf',\n];\n\n/**\n * Extends an object with another object.\n * This operates 'in-place'; it does not create a new Object.\n * Example:\n * var o = {};\n * extend(o, {a: 0, b: 1});\n * o; // {a: 0, b: 1}\n * extend(o, {b: 2, c: 3});\n * o; // {a: 0, b: 2, c: 3}\n * @param {?Object} target The object to modify. Existing properties will be\n * overwritten if they are also present in one of the objects in `var_args`.\n * @param {...(?Object|undefined)} var_args The objects from which values\n * will be copied.\n * @return {void}\n * @deprecated Prefer Object.assign\n */\nfunction extend(target, var_args) {\n let key;\n let source;\n for (let i = 1; i < arguments.length; i++) {\n source = arguments[i];\n for (key in source) {\n target[key] = source[key];\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n\n for (let j = 0; j < PROTOTYPE_FIELDS.length; j++) {\n key = PROTOTYPE_FIELDS[j];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n}\n\n/**\n * Creates a new object built from the key-value pairs provided as arguments.\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise even arguments are used as\n * the property names and odd arguments are used as the property values.\n * @return {!Object} The new object.\n * @throws {!Error} If there are uneven number of arguments or there is only one\n * non array argument.\n */\nfunction create(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return create.apply(null, arguments[0]);\n }\n\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i += 2) {\n rv[arguments[i]] = arguments[i + 1];\n }\n return rv;\n}\n\n/**\n * Creates a new object where the property names come from the arguments but\n * the value is always set to true\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise the arguments are used as\n * the property names.\n * @return {!Object} The new object.\n */\nfunction createSet(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return createSet.apply(null, arguments[0]);\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i++) {\n rv[arguments[i]] = true;\n }\n return rv;\n}\n\n/**\n * Creates an immutable view of the underlying object, if the browser\n * supports immutable objects.\n * In default mode, writes to this view will fail silently. In strict mode,\n * they will throw an error.\n * @param {!Object<K,V>} obj An object.\n * @return {!Object<K,V>} An immutable view of that object, or the original\n * object if this browser does not support immutables.\n * @template K,V\n */\nfunction createImmutableView(obj) {\n let result = obj;\n if (Object.isFrozen && !Object.isFrozen(obj)) {\n result = Object.create(obj);\n Object.freeze(result);\n }\n return result;\n}\n\n/**\n * @param {!Object} obj An object.\n * @return {boolean} Whether this is an immutable view of the object.\n */\nfunction isImmutableView(obj) {\n return !!Object.isFrozen && Object.isFrozen(obj);\n}\n\n/**\n * Get all properties names on a given Object regardless of enumerability.\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\n * `Object.getPrototypeOf` then this is equivalent to using\n * `getKeys`\n * @param {?Object} obj The object to get the properties of.\n * @param {boolean=} includeObjectPrototype Whether properties defined on\n * `Object.prototype` should be included in the result.\n * @param {boolean=} includeFunctionPrototype Whether properties defined on\n * `Function.prototype` should be included in the result.\n * @return {!Array<string>}\n * @public\n */\nfunction getAllPropertyNames(\n obj, includeObjectPrototype = undefined,\n includeFunctionPrototype = undefined) {\n if (!obj) {\n return [];\n }\n\n // Naively use a for..in loop to get the property names if the browser doesn't\n // support any other APIs for getting it.\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\n return getKeys(obj);\n }\n\n const visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n let proto = obj;\n while (proto && (proto !== Object.prototype || !!includeObjectPrototype) &&\n (proto !== Function.prototype || !!includeFunctionPrototype)) {\n const names = Object.getOwnPropertyNames(proto);\n for (let i = 0; i < names.length; i++) {\n visitedSet[names[i]] = true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n\n return getKeys(visitedSet);\n}\n\n/**\n * Given a ES5 or ES6 class reference, return its super class / super\n * constructor.\n * This should be used in rare cases where you need to walk up the inheritance\n * tree (this is generally a bad idea). But this work with ES5 and ES6 classes,\n * unlike relying on the superClass_ property.\n * Note: To start walking up the hierarchy from an instance call this with its\n * `constructor` property; e.g. `getSuperClass(instance.constructor)`.\n * @param {function(new: ?)} constructor\n * @return {?Object}\n */\nfunction getSuperClass(constructor) {\n const proto = Object.getPrototypeOf(constructor.prototype);\n return proto && proto.constructor;\n}\n\nexports = {\n add,\n clear,\n clone,\n contains,\n containsKey,\n containsValue,\n create,\n createImmutableView,\n createSet,\n equals,\n every,\n extend,\n filter,\n findKey,\n findValue,\n forEach,\n get,\n getAllPropertyNames,\n getAnyKey,\n getAnyValue,\n getCount,\n getKeys,\n getSuperClass,\n getValueByKeys,\n getValues,\n isEmpty,\n isImmutableView,\n map,\n remove,\n set,\n setIfUndefined,\n setWithReturnValueIfNotSet,\n some,\n transpose,\n unsafeClone,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An event manager for both native browser event\n * targets and custom JavaScript event targets\n * (`goog.events.Listenable`). This provides an abstraction\n * over browsers' event systems.\n *\n * It also provides a simulation of W3C event model's capture phase in\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\n * interact well with listeners registered directly on the elements\n * (bypassing goog.events) or even with listeners registered via\n * goog.events in a separate JS binary. In these cases, we provide\n * no ordering guarantees.\n *\n * The listeners will receive a \"patched\" event object. Such event object\n * contains normalized values for certain event properties that differs in\n * different browsers.\n *\n * Example usage:\n * <pre>\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\n * goog.events.removeAll(myNode);\n * </pre>\n *\n * in IE and event object patching]\n *\n * @see ../demos/events.html\n * @see ../demos/event-propagation.html\n * @see ../demos/stopevent.html\n */\n\n// IMPLEMENTATION NOTES:\n// goog.events stores an auxiliary data structure on each EventTarget\n// source being listened on. This allows us to take advantage of GC,\n// having the data structure GC'd when the EventTarget is GC'd. This\n// GC behavior is equivalent to using W3C DOM Events directly.\n\ngoog.provide('goog.events');\ngoog.provide('goog.events.CaptureSimulationMode');\ngoog.provide('goog.events.Key');\ngoog.provide('goog.events.ListenableType');\n\ngoog.require('goog.asserts');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.BrowserEvent');\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.EventWrapper');\ngoog.requireType('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listener');\n\n\n/**\n * @typedef {number|goog.events.ListenableKey}\n */\ngoog.events.Key;\n\n\n/**\n * @typedef {EventTarget|goog.events.Listenable}\n */\ngoog.events.ListenableType;\n\n\n/**\n * Property name on a native event target for the listener map\n * associated with the event target.\n * @private @const {string}\n */\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * String used to prepend to IE event types.\n * @const\n * @private\n */\ngoog.events.onString_ = 'on';\n\n\n/**\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\n * this removes an extra object allocation in goog.events.listen which\n * improves IE6 performance.\n * @const\n * @dict\n * @private\n */\ngoog.events.onStringMap_ = {};\n\n\n/**\n * @enum {number} Different capture simulation mode for IE8-.\n */\ngoog.events.CaptureSimulationMode = {\n /**\n * Does not perform capture simulation. Will asserts in IE8- when you\n * add capture listeners.\n */\n OFF_AND_FAIL: 0,\n\n /**\n * Does not perform capture simulation, silently ignore capture\n * listeners.\n */\n OFF_AND_SILENT: 1,\n\n /**\n * Performs capture simulation.\n */\n ON: 2\n};\n\n\n/**\n * @define {number} The capture simulation mode for IE8-. By default,\n * this is ON.\n */\ngoog.events.CAPTURE_SIMULATION_MODE =\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\n\n\n/**\n * Estimated count of total native listeners.\n * @private {number}\n */\ngoog.events.listenerCountEstimate_ = 0;\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. A listener can only be added once\n * to an object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method, or an object with a handleEvent function.\n * WARNING: passing an Object is now softly deprecated.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n */\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (opt_options && opt_options.once) {\n return goog.events.listenOnce(\n src, type, listener, opt_options, opt_handler);\n }\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listen(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ false, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target. A listener can only be added once to an object and if it\n * is added again the key for the listener is returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {EventTarget} src The node to listen to events on.\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\n * @param {!Function} listener Callback function.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener or otherwise.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} Unique key for the listener.\n * @template EVENTOBJ\n * @private\n */\ngoog.events.listen_ = function(\n src, type, listener, callOnce, opt_options, opt_handler) {\n 'use strict';\n if (!type) {\n throw new Error('Invalid event type');\n }\n\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n var listenerMap = goog.events.getListenerMap_(src);\n if (!listenerMap) {\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\n new goog.events.ListenerMap(src);\n }\n\n var listenerObj = /** @type {goog.events.Listener} */ (\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\n\n // If the listenerObj already has a proxy, it has been set up\n // previously. We simply return.\n if (listenerObj.proxy) {\n return listenerObj;\n }\n\n var proxy = goog.events.getProxy();\n listenerObj.proxy = proxy;\n\n proxy.src = src;\n proxy.listener = listenerObj;\n\n // Attach the proxy through the browser's API\n if (src.addEventListener) {\n // Don't pass an object as `capture` if the browser doesn't support that.\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\n opt_options = capture;\n }\n // Don't break tests that expect a boolean.\n if (opt_options === undefined) opt_options = false;\n src.addEventListener(type.toString(), proxy, opt_options);\n } else if (src.attachEvent) {\n // The else if above used to be an unconditional else. It would call\n // attachEvent come gws or high water. This would sometimes throw an\n // exception on IE11, spoiling the day of some callers. The previous\n // incarnation of this code, from 2007, indicates that it replaced an\n // earlier still version that caused excess allocations on IE6.\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\n } else if (src.addListener && src.removeListener) {\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\n // Safari, there is no global for the MediaQueryList constructor, so we just\n // check whether the object \"looks like\" MediaQueryList.\n goog.asserts.assert(\n type === 'change', 'MediaQueryList only has a change event');\n src.addListener(proxy);\n } else {\n throw new Error('addEventListener and attachEvent are unavailable.');\n }\n\n goog.events.listenerCountEstimate_++;\n return listenerObj;\n};\n\n\n/**\n * Helper function for returning a proxy function.\n * @return {!Function} A new or reused function object.\n */\ngoog.events.getProxy = function() {\n 'use strict';\n const proxyCallbackFunction = goog.events.handleBrowserEvent_;\n const f = function(eventObject) {\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\n };\n return f;\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. After the event has fired the event\n * listener is removed from the target.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n */\ngoog.events.listenOnce = function(\n src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listenOnce(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ true, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.Listenable}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.Listenable} src The target to\n * listen to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @template T\n */\ngoog.events.listenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.listen(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes an event listener which was added with listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {?boolean} indicating whether the listener was there to remove.\n * @template EVENTOBJ\n */\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.unlisten(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return false;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n var listenerObj = listenerMap.getListener(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n if (listenerObj) {\n return goog.events.unlistenByKey(listenerObj);\n }\n }\n\n return false;\n};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {goog.events.Key} key The key returned by listen() for this\n * event listener.\n * @return {boolean} indicating whether the listener was there to remove.\n */\ngoog.events.unlistenByKey = function(key) {\n 'use strict';\n // TODO(chrishenry): Remove this check when tests that rely on this\n // are fixed.\n if (typeof key === 'number') {\n return false;\n }\n\n var listener = key;\n if (!listener || listener.removed) {\n return false;\n }\n\n var src = listener.src;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\n }\n\n var type = listener.type;\n var proxy = listener.proxy;\n if (src.removeEventListener) {\n src.removeEventListener(type, proxy, listener.capture);\n } else if (src.detachEvent) {\n src.detachEvent(goog.events.getOnString_(type), proxy);\n } else if (src.addListener && src.removeListener) {\n src.removeListener(proxy);\n }\n goog.events.listenerCountEstimate_--;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n // TODO(chrishenry): Try to remove this conditional and execute the\n // first branch always. This should be safe.\n if (listenerMap) {\n listenerMap.removeByKey(listener);\n if (listenerMap.getTypeCount() == 0) {\n // Null the src, just because this is simple to do (and useful\n // for IE <= 7).\n listenerMap.src = null;\n // We don't use delete here because IE does not allow delete\n // on a window object.\n src[goog.events.LISTENER_MAP_PROP_] = null;\n }\n } else {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n }\n\n return true;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n */\ngoog.events.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes all listeners from an object. You can also optionally\n * remove listeners of a particular type.\n *\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\n * EventTarget or a goog.events.Listenable.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * Default is all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.removeAll = function(obj, opt_type) {\n 'use strict';\n // TODO(chrishenry): Change the type of obj to\n // (!EventTarget|!goog.events.Listenable).\n\n if (!obj) {\n return 0;\n }\n\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n if (!listenerMap) {\n return 0;\n }\n\n var count = 0;\n var typeStr = opt_type && opt_type.toString();\n for (var type in listenerMap.listeners) {\n if (!typeStr || type == typeStr) {\n // Clone so that we don't need to worry about unlistenByKey\n // changing the content of the ListenerMap.\n var listeners = listenerMap.listeners[type].concat();\n for (var i = 0; i < listeners.length; ++i) {\n if (goog.events.unlistenByKey(listeners[i])) {\n ++count;\n }\n }\n }\n }\n return count;\n};\n\n\n/**\n * Gets the listeners for a given object, type and capture phase.\n *\n * @param {Object} obj Object to get listeners for.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Capture phase?.\n * @return {!Array<!goog.events.Listener>} Array of listener objects.\n */\ngoog.events.getListeners = function(obj, type, capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\n type, capture);\n } else {\n if (!obj) {\n // TODO(chrishenry): We should tighten the API to accept\n // !EventTarget|goog.events.Listenable, and add an assertion here.\n return [];\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\n }\n};\n\n\n/**\n * Gets the goog.events.Listener for the event or null if no such listener is\n * in use.\n *\n * @param {EventTarget|goog.events.Listenable} src The target from\n * which to get listeners.\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\n * listener function to get.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the\n * capture or bubble phase of the event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n * @template EVENTOBJ\n */\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\n 'use strict';\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\n type = /** @type {string} */ (type);\n listener = goog.events.wrapListener(listener);\n var capture = !!opt_capt;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.getListener(type, listener, capture, opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return null;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n return listenerMap.getListener(type, listener, capture, opt_handler);\n }\n return null;\n};\n\n\n/**\n * Returns whether an event target has any active listeners matching the\n * specified signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {EventTarget|goog.events.Listenable} obj Target to get\n * listeners for.\n * @param {string|!goog.events.EventId=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\n * listeners.\n * @return {boolean} Whether an event target has one or more listeners matching\n * the requested type and/or capture phase.\n */\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return obj.hasListener(opt_type, opt_capture);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\n};\n\n\n/**\n * Provides a nice string showing the normalized event objects public members\n * @param {Object} e Event Object.\n * @return {string} String of the public members of the normalized event object.\n */\ngoog.events.expose = function(e) {\n 'use strict';\n var str = [];\n for (var key in e) {\n if (e[key] && e[key].id) {\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\n } else {\n str.push(key + ' = ' + e[key]);\n }\n }\n return str.join('\\n');\n};\n\n\n/**\n * Returns a string with on prepended to the specified type. This is used for IE\n * which expects \"on\" to be prepended. This function caches the string in order\n * to avoid extra allocations in steady state.\n * @param {string} type Event type.\n * @return {string} The type string with 'on' prepended.\n * @private\n */\ngoog.events.getOnString_ = function(type) {\n 'use strict';\n if (type in goog.events.onStringMap_) {\n return goog.events.onStringMap_[type];\n }\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase\n *\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n */\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\n type, capture, eventObject);\n }\n\n return goog.events.fireListeners_(obj, type, capture, eventObject);\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase.\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n * @private\n */\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\n 'use strict';\n /** @type {boolean} */\n var retval = true;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {EventTarget} */ (obj));\n if (listenerMap) {\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // listenerMap.getListeners(type, capture) instead, which is simpler.\n var listenerArray = listenerMap.listeners[type.toString()];\n if (listenerArray) {\n listenerArray = listenerArray.concat();\n for (var i = 0; i < listenerArray.length; i++) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && listener.capture == capture && !listener.removed) {\n var result = goog.events.fireListener(listener, eventObject);\n retval = retval && (result !== false);\n }\n }\n }\n }\n return retval;\n};\n\n\n/**\n * Fires a listener with a set of arguments\n *\n * @param {goog.events.Listener} listener The listener object to call.\n * @param {Object} eventObject The event object to pass to the listener.\n * @return {*} Result of listener.\n */\ngoog.events.fireListener = function(listener, eventObject) {\n 'use strict';\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n goog.events.unlistenByKey(listener);\n }\n return listenerFn.call(listenerHandler, eventObject);\n};\n\n\n/**\n * Gets the total number of listeners currently in the system.\n * @return {number} Number of listeners.\n * @deprecated This returns estimated count, now that Closure no longer\n * stores a central listener registry. We still return an estimation\n * to keep existing listener-related tests passing. In the near future,\n * this function will be removed.\n */\ngoog.events.getTotalListenerCount = function() {\n 'use strict';\n return goog.events.listenerCountEstimate_;\n};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {goog.events.Listenable} src The event target.\n * @param {goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the handlers returns false) this will also return false.\n * If there are no handlers, or if all handlers return true, this returns\n * true.\n */\ngoog.events.dispatchEvent = function(src, e) {\n 'use strict';\n goog.asserts.assert(\n goog.events.Listenable.isImplementedBy(src),\n 'Can not use goog.events.dispatchEvent with ' +\n 'non-goog.events.Listenable instance.');\n return src.dispatchEvent(e);\n};\n\n\n/**\n * Installs exception protection for the browser event entry point using the\n * given error handler.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point.\n */\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\n};\n\n\n/**\n * Handles an event and dispatches it to the correct listeners. This\n * function is a proxy for the real listener the user specified.\n *\n * @param {goog.events.Listener} listener The listener object.\n * @param {Event=} opt_evt Optional event object that gets passed in via the\n * native event handlers.\n * @return {*} Result of the event handler.\n * @this {EventTarget} The object or Element that fired the event.\n * @private\n */\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\n 'use strict';\n if (listener.removed) {\n return true;\n }\n\n // Otherwise, simply fire the listener.\n return goog.events.fireListener(\n listener, new goog.events.BrowserEvent(opt_evt, this));\n};\n\n\n/**\n * This is used to mark the IE event object so we do not do the Closure pass\n * twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @private\n */\ngoog.events.markIeEvent_ = function(e) {\n 'use strict';\n // Only the keyCode and the returnValue can be changed. We use keyCode for\n // non keyboard events.\n // event.returnValue is a bit more tricky. It is undefined by default. A\n // boolean false prevents the default action. In a window.onbeforeunload and\n // the returnValue is non undefined it will be alerted. However, we will only\n // modify the returnValue for keyboard events. We can get a problem if non\n // closure events sets the keyCode or the returnValue\n\n var useReturnValue = false;\n\n if (e.keyCode == 0) {\n // We cannot change the keyCode in case that srcElement is input[type=file].\n // We could test that that is the case but that would allocate 3 objects.\n // If we use try/catch we will only allocate extra objects in the case of a\n // failure.\n\n try {\n e.keyCode = -1;\n return;\n } catch (ex) {\n useReturnValue = true;\n }\n }\n\n if (useReturnValue ||\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\n e.returnValue = true;\n }\n};\n\n\n/**\n * This is used to check if an IE event has already been handled by the Closure\n * system so we do not do the Closure pass twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @return {boolean} True if the event object has been marked.\n * @private\n */\ngoog.events.isMarkedIeEvent_ = function(e) {\n 'use strict';\n return e.keyCode < 0 || e.returnValue != undefined;\n};\n\n\n/**\n * Counter to create unique event ids.\n * @private {number}\n */\ngoog.events.uniqueIdCounter_ = 0;\n\n\n/**\n * Creates a unique event id.\n *\n * @param {string} identifier The identifier.\n * @return {string} A unique identifier.\n * @idGenerator {unique}\n */\ngoog.events.getUniqueId = function(identifier) {\n 'use strict';\n return identifier + '_' + goog.events.uniqueIdCounter_++;\n};\n\n\n/**\n * @param {EventTarget} src The source object.\n * @return {goog.events.ListenerMap} A listener map for the given\n * source object, or null if none exists.\n * @private\n */\ngoog.events.getListenerMap_ = function(src) {\n 'use strict';\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\n // IE serializes the property as well (e.g. when serializing outer\n // HTML). So we must check that the value is of the correct type.\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\n};\n\n\n/**\n * Expando property for listener function wrapper for Object with\n * handleEvent.\n * @private @const {string}\n */\ngoog.events.LISTENER_WRAPPER_PROP_ =\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * @param {Object|Function} listener The listener function or an\n * object that contains handleEvent method.\n * @return {!Function} Either the original function or a function that\n * calls obj.handleEvent. If the same listener is passed to this\n * function more than once, the same function is guaranteed to be\n * returned.\n */\ngoog.events.wrapListener = function(listener) {\n 'use strict';\n goog.asserts.assert(listener, 'Listener can not be null.');\n\n if (typeof listener === 'function') {\n return listener;\n }\n\n goog.asserts.assert(\n listener.handleEvent, 'An object listener must have handleEvent method.');\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\n 'use strict';\n return /** @type {?} */ (listener).handleEvent(e);\n };\n }\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\n};\n\n\n// Register the browser event handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n transformer(goog.events.handleBrowserEvent_);\n });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @see ../demos/eventtarget.html\n * @see goog.events.Listenable\n */\n\ngoog.provide('goog.events.EventTarget');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.asserts');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * An implementation of `goog.events.Listenable` with full W3C\n * EventTarget-like support (capture/bubble mechanism, stopping event\n * propagation, preventing default actions).\n *\n * You may subclass this class to turn your class into a Listenable.\n *\n * Unless propagation is stopped, an event dispatched by an\n * EventTarget will bubble to the parent returned by\n * `getParentEventTarget`. To set the parent, call\n * `setParentEventTarget`. Subclasses that don't support\n * changing the parent can override the setter to throw an error.\n *\n * Example usage:\n * <pre>\n * var source = new goog.events.EventTarget();\n * function handleEvent(e) {\n * alert('Type: ' + e.type + '; Target: ' + e.target);\n * }\n * source.listen('foo', handleEvent);\n * // Or: goog.events.listen(source, 'foo', handleEvent);\n * ...\n * source.dispatchEvent('foo'); // will call handleEvent\n * ...\n * source.unlisten('foo', handleEvent);\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\n * </pre>\n *\n * @constructor\n * @extends {goog.Disposable}\n * @implements {goog.events.Listenable}\n */\ngoog.events.EventTarget = function() {\n 'use strict';\n goog.Disposable.call(this);\n\n /**\n * Maps of event type to an array of listeners.\n * @private {!goog.events.ListenerMap}\n */\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\n\n /**\n * The object to use for event.target. Useful when mixing in an\n * EventTarget to another object.\n * @private {!Object}\n */\n this.actualEventTarget_ = this;\n\n /**\n * Parent event target, used during event bubbling.\n *\n * TODO(chrishenry): Change this to goog.events.Listenable. This\n * currently breaks people who expect getParentEventTarget to return\n * goog.events.EventTarget.\n *\n * @private {?goog.events.EventTarget}\n */\n this.parentEventTarget_ = null;\n};\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\n\n\n/**\n * An artificial cap on the number of ancestors you can have. This is mainly\n * for loop detection.\n * @const {number}\n * @private\n */\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\n\n\n/**\n * Returns the parent of this event target to use for bubbling.\n *\n * @return {goog.events.EventTarget} The parent EventTarget or null if\n * there is no parent.\n * @override\n */\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\n 'use strict';\n return this.parentEventTarget_;\n};\n\n\n/**\n * Sets the parent of this event target to use for capture/bubble\n * mechanism.\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\n */\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\n 'use strict';\n this.parentEventTarget_ = parent;\n};\n\n\n/**\n * Adds an event listener to the event target. The same handler can only be\n * added once per the type. Even if you add the same handler multiple times\n * using the same type then it will only be called once when the event is\n * dispatched.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\n * `goog.events.listen` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.addEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * Removes an event listener from the event target. The handler must be the\n * same object as the one added. If the handler has not been added then\n * nothing is done.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\n * `goog.events.unlisten` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.removeEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @override\n */\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\n 'use strict';\n this.assertInitialized_();\n\n var ancestorsTree, ancestor = this.getParentEventTarget();\n if (ancestor) {\n ancestorsTree = [];\n var ancestorCount = 1;\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\n ancestorsTree.push(ancestor);\n goog.asserts.assert(\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\n 'infinite loop');\n }\n }\n\n return goog.events.EventTarget.dispatchEventInternal_(\n this.actualEventTarget_, e, ancestorsTree);\n};\n\n\n/**\n * Removes listeners from this object. Classes that extend EventTarget may\n * need to override this method in order to remove references to DOM Elements\n * and additional listeners.\n * @override\n * @protected\n */\ngoog.events.EventTarget.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\n\n this.removeAllListeners();\n this.parentEventTarget_ = null;\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n this.assertInitialized_();\n return this.eventTargetListeners_.add(\n String(type), listener, false /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.add(\n String(type), listener, true /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.remove(\n String(type), listener, opt_useCapture, opt_listenerScope);\n};\n\n\n/**\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n * @override\n */\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\n 'use strict';\n return this.eventTargetListeners_.removeByKey(key);\n};\n\n\n/**\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n * @override\n */\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\n 'use strict';\n // TODO(chrishenry): Previously, removeAllListeners can be called on\n // uninitialized EventTarget, so we preserve that behavior. We\n // should remove this when usages that rely on that fact are purged.\n if (!this.eventTargetListeners_) {\n return 0;\n }\n return this.eventTargetListeners_.removeAll(opt_type);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.fireListeners = function(\n type, capture, eventObject) {\n 'use strict';\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // getListeners(type, capture) instead, which is simpler.\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\n if (!listenerArray) {\n return true;\n }\n listenerArray = listenerArray.concat();\n\n var rv = true;\n for (var i = 0; i < listenerArray.length; ++i) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && !listener.removed && listener.capture == capture) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n this.unlistenByKey(listener);\n }\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\n }\n }\n\n return rv && !eventObject.defaultPrevented;\n};\n\n\n/**\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\n 'use strict';\n return this.eventTargetListeners_.getListeners(String(type), capture);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.getListener(\n String(type), listener, capture, opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var id = (opt_type !== undefined) ? String(opt_type) : undefined;\n return this.eventTargetListeners_.hasListener(id, opt_capture);\n};\n\n\n/**\n * Sets the target to be used for `event.target` when firing\n * event. Mainly used for testing. For example, see\n * `goog.testing.events.mixinListenable`.\n * @param {!Object} target The target.\n */\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\n 'use strict';\n this.actualEventTarget_ = target;\n};\n\n\n/**\n * Asserts that the event target instance is initialized properly.\n * @private\n */\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\n 'use strict';\n goog.asserts.assert(\n this.eventTargetListeners_,\n 'Event target is not initialized. Did you call the superclass ' +\n '(goog.events.EventTarget) constructor?');\n};\n\n\n/**\n * Dispatches the given event on the ancestorsTree.\n *\n * @param {!Object} target The target to dispatch on.\n * @param {goog.events.Event|Object|string} e The event object.\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\n * tree of the target, in reverse order from the closest ancestor\n * to the root event target. May be null if the target has no ancestor.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @private\n */\ngoog.events.EventTarget.dispatchEventInternal_ = function(\n target, e, opt_ancestorsTree) {\n 'use strict';\n /** @suppress {missingProperties} */\n var type = e.type || /** @type {string} */ (e);\n\n // If accepting a string or object, create a custom event object so that\n // preventDefault and stopPropagation work with the event.\n if (typeof e === 'string') {\n e = new goog.events.Event(e, target);\n } else if (!(e instanceof goog.events.Event)) {\n var oldEvent = e;\n e = new goog.events.Event(type, target);\n goog.object.extend(e, oldEvent);\n } else {\n e.target = e.target || target;\n }\n\n var rv = true, currentTarget;\n\n // Executes all capture listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (var i = opt_ancestorsTree.length - 1;\n !e.hasPropagationStopped() && i >= 0; i--) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, true, e) && rv;\n }\n }\n\n // Executes capture and bubble listeners on the target.\n if (!e.hasPropagationStopped()) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.hasPropagationStopped()) {\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n // Executes all bubble listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (i = 0; !e.hasPropagationStopped() && i < opt_ancestorsTree.length;\n i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview JSON utility functions.\n */\n\n\ngoog.provide('goog.json');\ngoog.provide('goog.json.Replacer');\ngoog.provide('goog.json.Reviver');\ngoog.provide('goog.json.Serializer');\n\n\n/**\n * @define {boolean} If true, use the native JSON parsing API.\n * NOTE: The default `goog.json.parse` implementation is able to handle\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\n * faster and safer than the default implementation using `eval`.\n */\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\n\n/**\n * @define {boolean} If true, try the native JSON parsing API first. If it\n * fails, log an error and use `eval` instead. This is useful when\n * transitioning to `goog.json.USE_NATIVE_JSON`. The error logger needs to\n * be set by `goog.json.setErrorLogger`. If it is not set then the error\n * is ignored.\n */\ngoog.json.TRY_NATIVE_JSON = goog.define('goog.json.TRY_NATIVE_JSON', true);\n\n\n/**\n * Tests if a string is an invalid JSON string. This only ensures that we are\n * not using any invalid characters\n * @param {string} s The string to test.\n * @return {boolean} True if the input is a valid JSON string.\n */\ngoog.json.isValid = function(s) {\n 'use strict';\n // All empty whitespace is not valid.\n if (/^\\s*$/.test(s)) {\n return false;\n }\n\n // This is taken from http://www.json.org/json2.js which is released to the\n // public domain.\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\n // are in the RFC but IE and Safari does not match \\s to these so we need to\n // include them in the reg exps in all places where whitespace is allowed.\n // We allowed \\x7f inside strings because some tools don't escape it,\n // e.g. http://www.json.org/java/org/json/JSONObject.java\n\n // Parsing happens in three stages. In the first stage, we run the text\n // against regular expressions that look for non-JSON patterns. We are\n // especially concerned with '()' and 'new' because they can cause invocation,\n // and '=' because it can cause mutation. But just to be safe, we want to\n // reject all unexpected forms.\n\n // We split the first stage into 4 regexp operations in order to work around\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\n // replace all simple value tokens with ']' characters, but only when followed\n // by a colon, comma, closing bracket or end of string. Third, we delete all\n // open brackets that follow a colon or comma or that begin the text. Finally,\n // we look to see that the remaining characters are only whitespace or ']' or\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\n\n // Don't make these static since they have the global flag.\n const backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n const simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n const openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n const remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\n\n return remainderRe.test(\n s.replace(backslashesRe, '@')\n .replace(simpleValuesRe, ']')\n .replace(openBracketsRe, ''));\n};\n\n/**\n * Logs a parsing error in `JSON.parse` solvable by using `eval`\n * if `goog.json.TRY_NATIVE_JSON` is enabled.\n * @private {function(string, !Error)} The first parameter is the error message,\n * the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.errorLogger_ = goog.nullFunction;\n\n\n/**\n * Sets an error logger to use if there's a recoverable parsing error and\n * `goog.json.TRY_NATIVE_JSON` is enabled.\n * @param {function(string, !Error)} errorLogger The first parameter is the\n * error message, the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.setErrorLogger = function(errorLogger) {\n 'use strict';\n goog.json.errorLogger_ = errorLogger;\n};\n\n\n/**\n * Parses a JSON string and returns the result. This throws an exception if\n * the string is an invalid JSON string.\n *\n * Note that this is very slow on large strings. Use JSON.parse if possible.\n *\n * @param {*} s The JSON string to parse.\n * @throws Error if s is invalid JSON.\n * @return {Object} The object generated from the JSON string, or null.\n * @deprecated Use JSON.parse.\n */\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\n function(s) {\n 'use strict';\n let error;\n if (goog.json.TRY_NATIVE_JSON) {\n try {\n return goog.global['JSON']['parse'](s);\n } catch (ex) {\n error = ex;\n }\n }\n const o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n const result = /** @type {?Object} */ (eval('(' + o + ')'));\n if (error) {\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\n }\n return result;\n } catch (ex) {\n }\n }\n throw new Error('Invalid JSON string: ' + o);\n };\n\n\n/**\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * TODO(nicksantos): Array should also be a valid replacer.\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Replacer;\n\n\n/**\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Reviver;\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\n * called for each (key, value) pair that determines how the value\n * should be serialized. By defult, this just returns the value\n * and allows default serialization to kick in.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*, ?goog.json.Replacer=):string} */\n (goog.global['JSON']['stringify']) :\n function(object, opt_replacer) {\n 'use strict';\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\n //\n // The last time I evaluated this, JSON.stringify had subtle bugs and\n // behavior differences on all browsers, and the performance win was not\n // large enough to justify all the issues. This may change in the future\n // as browser implementations get better.\n //\n // assertSerialize in json_test contains if branches for the cases\n // that fail.\n return new goog.json.Serializer(opt_replacer).serialize(object);\n };\n\n\n\n/**\n * Class that is used to serialize JSON objects to a string.\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\n * @constructor\n */\ngoog.json.Serializer = function(opt_replacer) {\n 'use strict';\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n};\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.Serializer.prototype.serialize = function(object) {\n 'use strict';\n const sb = [];\n this.serializeInternal(object, sb);\n return sb.join('');\n};\n\n\n/**\n * Serializes a generic value to a JSON string\n * @protected\n * @param {*} object The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @throws Error if there are loops in the object graph.\n */\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\n 'use strict';\n if (object == null) {\n // undefined == null so this branch covers undefined as well as null\n sb.push('null');\n return;\n }\n\n if (typeof object == 'object') {\n if (Array.isArray(object)) {\n this.serializeArray(object, sb);\n return;\n } else if (\n object instanceof String || object instanceof Number ||\n object instanceof Boolean) {\n object = object.valueOf();\n // Fall through to switch below.\n } else {\n this.serializeObject_(/** @type {!Object} */ (object), sb);\n return;\n }\n }\n\n switch (typeof object) {\n case 'string':\n this.serializeString_(object, sb);\n break;\n case 'number':\n this.serializeNumber_(object, sb);\n break;\n case 'boolean':\n sb.push(String(object));\n break;\n case 'function':\n sb.push('null');\n break;\n default:\n throw new Error('Unknown type: ' + typeof object);\n }\n};\n\n\n/**\n * Character mappings used internally for goog.string.quote\n * @private\n * @type {!Object}\n */\ngoog.json.Serializer.charToJsonCharCache_ = {\n '\\\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '/': '\\\\/',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\n};\n\n\n/**\n * Regular expression used to match characters that need to be replaced.\n * The S60 browser has a bug where unicode characters are not matched by\n * regular expressions. The condition below detects such behaviour and\n * adjusts the regular expression accordingly.\n * @private\n * @type {!RegExp}\n */\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\n\n\n/**\n * Serializes a string to a JSON string\n * @private\n * @param {string} s The string to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\n 'use strict';\n // The official JSON implementation does not work with international\n // characters.\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\n 'use strict';\n // caching the result improves performance by a factor 2-3\n let rv = goog.json.Serializer.charToJsonCharCache_[c];\n if (!rv) {\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\n }\n return rv;\n }), '\"');\n};\n\n\n/**\n * Serializes a number to a JSON string\n * @private\n * @param {number} n The number to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\n 'use strict';\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\n};\n\n\n/**\n * Serializes an array to a JSON string\n * @param {Array<string>} arr The array to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @protected\n */\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\n 'use strict';\n const l = arr.length;\n sb.push('[');\n let sep = '';\n for (let i = 0; i < l; i++) {\n sb.push(sep);\n\n const value = arr[i];\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\n sb);\n\n sep = ',';\n }\n sb.push(']');\n};\n\n\n/**\n * Serializes an object to a JSON string\n * @private\n * @param {!Object} obj The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\n 'use strict';\n sb.push('{');\n let sep = '';\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n // Skip functions.\n if (typeof value != 'function') {\n sb.push(sep);\n this.serializeString_(key, sb);\n sb.push(':');\n\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\n\n sep = ',';\n }\n }\n }\n sb.push('}');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.module('goog.async.WorkQueue');\ngoog.module.declareLegacyNamespace();\n\nconst FreeList = goog.require('goog.async.FreeList');\nconst {assert} = goog.require('goog.asserts');\n\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\n// than goog.async.run.\n\n\n/**\n * A low GC workqueue. The key elements of this design:\n * - avoids the need for goog.bind or equivalent by carrying scope\n * - avoids the need for array reallocation by using a linked list\n * - minimizes work entry objects allocation by recycling objects\n * @final\n * @struct\n */\nclass WorkQueue {\n constructor() {\n this.workHead_ = null;\n this.workTail_ = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n add(fn, scope) {\n const item = this.getUnusedItem_();\n item.set(fn, scope);\n\n if (this.workTail_) {\n this.workTail_.next = item;\n this.workTail_ = item;\n } else {\n assert(!this.workHead_);\n this.workHead_ = item;\n this.workTail_ = item;\n }\n }\n\n /**\n * @return {?WorkItem}\n */\n remove() {\n let item = null;\n\n if (this.workHead_) {\n item = this.workHead_;\n this.workHead_ = this.workHead_.next;\n if (!this.workHead_) {\n this.workTail_ = null;\n }\n item.next = null;\n }\n return item;\n }\n\n /**\n * @param {!WorkItem} item\n */\n returnUnused(item) {\n WorkQueue.freelist_.put(item);\n }\n\n /**\n * @return {!WorkItem}\n * @private\n */\n getUnusedItem_() {\n return WorkQueue.freelist_.get();\n }\n}\n\n/** @define {number} The maximum number of entries to keep for recycling. */\nWorkQueue.DEFAULT_MAX_UNUSED =\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\n\n/** @const @private {!FreeList<!WorkItem>} */\nWorkQueue.freelist_ = new FreeList(\n () => new WorkItem(), item => item.reset(), WorkQueue.DEFAULT_MAX_UNUSED);\n\n/**\n * @final\n * @struct\n */\nclass WorkItem {\n constructor() {\n /** @type {?function()} */\n this.fn = null;\n /** @type {?Object|null|undefined} */\n this.scope = null;\n /** @type {?WorkItem} */\n this.next = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n set(fn, scope) {\n 'use strict';\n this.fn = fn;\n this.scope = scope;\n this.next = null;\n }\n\n /** Reset the work item so they don't prevent GC before reuse */\n reset() {\n this.fn = null;\n this.scope = null;\n this.next = null;\n }\n}\n\nexports = WorkQueue;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.async.run');\n\ngoog.require('goog.async.WorkQueue');\ngoog.require('goog.async.nextTick');\ngoog.require('goog.async.throwException');\n\n/**\n * @define {boolean} If true, use the global Promise to implement goog.async.run\n * assuming either the native, or polyfill version will be used. Does still\n * permit tests to use forceNextTick.\n */\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\n\n/**\n * Fires the provided callback just before the current callstack unwinds, or as\n * soon as possible after the current JS execution context.\n * @param {function(this:THIS)} callback\n * @param {THIS=} opt_context Object to use as the \"this value\" when calling\n * the provided function.\n * @template THIS\n */\ngoog.async.run = function(callback, opt_context) {\n 'use strict';\n if (!goog.async.run.schedule_) {\n goog.async.run.initializeRunner_();\n }\n if (!goog.async.run.workQueueScheduled_) {\n // Nothing is currently scheduled, schedule it now.\n goog.async.run.schedule_();\n goog.async.run.workQueueScheduled_ = true;\n }\n\n goog.async.run.workQueue_.add(callback, opt_context);\n};\n\n\n/**\n * Initializes the function to use to process the work queue.\n * @private\n */\ngoog.async.run.initializeRunner_ = function() {\n 'use strict';\n if (goog.ASSUME_NATIVE_PROMISE ||\n (goog.global.Promise && goog.global.Promise.resolve)) {\n // Use goog.global.Promise instead of just Promise because the relevant\n // externs may be missing, and don't alias it because this could confuse the\n // compiler into thinking the polyfill is required when it should be treated\n // as optional.\n var promise = goog.global.Promise.resolve(undefined);\n goog.async.run.schedule_ = function() {\n 'use strict';\n promise.then(goog.async.run.processWorkQueue);\n };\n } else {\n goog.async.run.schedule_ = function() {\n 'use strict';\n goog.async.nextTick(goog.async.run.processWorkQueue);\n };\n }\n};\n\n\n/**\n * Forces goog.async.run to use nextTick instead of Promise.\n *\n * This should only be done in unit tests. It's useful because MockClock\n * replaces nextTick, but not the browser Promise implementation, so it allows\n * Promise-based code to be tested with MockClock.\n *\n * However, we also want to run promises if the MockClock is no longer in\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\n * provided.\n *\n * @param {function(function())=} opt_realSetTimeout\n */\ngoog.async.run.forceNextTick = function(opt_realSetTimeout) {\n 'use strict';\n goog.async.run.schedule_ = function() {\n 'use strict';\n goog.async.nextTick(goog.async.run.processWorkQueue);\n if (opt_realSetTimeout) {\n opt_realSetTimeout(goog.async.run.processWorkQueue);\n }\n };\n};\n\n\n/**\n * The function used to schedule work asynchronousely.\n * @private {function()}\n */\ngoog.async.run.schedule_;\n\n\n/** @private {boolean} */\ngoog.async.run.workQueueScheduled_ = false;\n\n\n/** @private {!goog.async.WorkQueue} */\ngoog.async.run.workQueue_ = new goog.async.WorkQueue();\n\n\nif (goog.DEBUG) {\n /**\n * Reset the work queue. Only available for tests in debug mode.\n */\n goog.async.run.resetQueue = function() {\n 'use strict';\n goog.async.run.workQueueScheduled_ = false;\n goog.async.run.workQueue_ = new goog.async.WorkQueue();\n };\n\n\n /**\n * Resets the scheduler. Only available for tests in debug mode.\n */\n goog.async.run.resetSchedulerForTest = function() {\n goog.async.run.initializeRunner_();\n };\n}\n\n\n/**\n * Run any pending goog.async.run work items. This function is not intended\n * for general use, but for use by entry point handlers to run items ahead of\n * goog.async.nextTick.\n */\ngoog.async.run.processWorkQueue = function() {\n 'use strict';\n // NOTE: additional work queue items may be added while processing.\n var item = null;\n while (item = goog.async.run.workQueue_.remove()) {\n try {\n item.fn.call(item.scope);\n } catch (e) {\n goog.async.throwException(e);\n }\n goog.async.run.workQueue_.returnUnused(item);\n }\n\n // There are no more work items, allow processing to be scheduled again.\n goog.async.run.workQueueScheduled_ = false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple freelist.\n *\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\n * objects in the list contain a \"next\" property that can be used to maintain\n * the pool.\n */\n\ngoog.provide('goog.async.FreeList');\n\n\n/**\n * @template ITEM\n */\ngoog.async.FreeList = class {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor(create, reset, limit) {\n /** @private @const {number} */\n this.limit_ = limit;\n /** @private @const {function()} */\n this.create_ = create;\n /** @private @const {function(ITEM):void} */\n this.reset_ = reset;\n\n /** @private {number} */\n this.occupants_ = 0;\n /** @private {ITEM} */\n this.head_ = null;\n }\n\n /**\n * @return {ITEM}\n */\n get() {\n let item;\n if (this.occupants_ > 0) {\n this.occupants_--;\n item = this.head_;\n this.head_ = item.next;\n item.next = null;\n } else {\n item = this.create_();\n }\n return item;\n }\n\n /**\n * @param {ITEM} item An item available for possible future reuse.\n */\n put(item) {\n this.reset_(item);\n if (this.occupants_ < this.limit_) {\n this.occupants_++;\n item.next = this.head_;\n this.head_ = item;\n }\n }\n\n /**\n * Visible for testing.\n * @package\n * @return {number}\n */\n occupants() {\n return this.occupants_;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a function to throw an error without interrupting\n * the current execution context.\n */\n\ngoog.module('goog.async.throwException');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Throw an item without interrupting the current execution context. For\n * example, if processing a group of items in a loop, sometimes it is useful\n * to report an error while still allowing the rest of the batch to be\n * processed.\n * @param {*} exception\n */\nfunction throwException(exception) {\n // Each throw needs to be in its own context.\n goog.global.setTimeout(() => {\n throw exception;\n }, 0);\n}\nexports = throwException;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A timer class to which other classes and objects can listen on.\n * This is only an abstraction above `setInterval`.\n *\n * @see ../demos/timers.html\n */\n\ngoog.provide('goog.Timer');\n\ngoog.require('goog.Promise');\ngoog.require('goog.events.EventTarget');\ngoog.requireType('goog.Thenable');\n\n\n\n/**\n * Class for handling timing events.\n *\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\n * `setInterval`, `clearTimeout` and `clearInterval`\n * (e.g., `window`).\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.Timer = function(opt_interval, opt_timerObject) {\n 'use strict';\n goog.events.EventTarget.call(this);\n\n /**\n * Number of ms between ticks\n * @private {number}\n */\n this.interval_ = opt_interval || 1;\n\n /**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the window\n * object. Changing this on {@link goog.Timer.prototype} changes the object\n * for all timer instances which can be useful if your environment has some\n * other implementation of timers than the `window` object.\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\n */\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\n opt_timerObject || goog.Timer.defaultTimerObject);\n\n /**\n * Cached `tick_` bound to the object for later use in the timer.\n * @private {Function}\n * @const\n */\n this.boundTick_ = goog.bind(this.tick_, this);\n\n /**\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\n * than the requested timeout. So we compare the time to when the event was\n * last fired, and reschedule if appropriate. See also\n * {@link goog.Timer.intervalScale}.\n * @private {number}\n */\n this.last_ = goog.now();\n};\ngoog.inherits(goog.Timer, goog.events.EventTarget);\n\n\n/**\n * Maximum timeout value.\n *\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\n * immediately. It makes more sense simply not to schedule these timeouts, since\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\n\n\n/**\n * A timer ID that cannot be returned by any known implementation of\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\n * should therefore be a no-op.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\n\n\n/**\n * Whether this timer is enabled\n * @type {boolean}\n */\ngoog.Timer.prototype.enabled = false;\n\n\n/**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the global\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\n * all timer instances which can be useful if your environment has some other\n * implementation of timers you'd like to use.\n * @type {{setTimeout, clearTimeout}}\n */\ngoog.Timer.defaultTimerObject = goog.global;\n\n\n/**\n * Variable that controls the timer error correction. If the timer is called\n * before the requested interval times `intervalScale`, which often\n * happens on Mozilla, the timer is rescheduled.\n * @see {@link #last_}\n * @type {number}\n */\ngoog.Timer.intervalScale = 0.8;\n\n\n/**\n * Variable for storing the result of `setInterval`.\n * @private {?number}\n */\ngoog.Timer.prototype.timer_ = null;\n\n\n/**\n * Gets the interval of the timer.\n * @return {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.getInterval = function() {\n 'use strict';\n return this.interval_;\n};\n\n\n/**\n * Sets the interval of the timer.\n * @param {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.setInterval = function(interval) {\n 'use strict';\n this.interval_ = interval;\n if (this.timer_ && this.enabled) {\n // Stop and then start the timer to reset the interval.\n this.stop();\n this.start();\n } else if (this.timer_) {\n this.stop();\n }\n};\n\n\n/**\n * Callback for the `setTimeout` used by the timer.\n * @private\n */\ngoog.Timer.prototype.tick_ = function() {\n 'use strict';\n if (this.enabled) {\n var elapsed = goog.now() - this.last_;\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\n this.timer_ = this.timerObject_.setTimeout(\n this.boundTick_, this.interval_ - elapsed);\n return;\n }\n\n // Prevents setInterval from registering a duplicate timeout when called\n // in the timer event handler.\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n\n this.dispatchTick();\n // The timer could be stopped in the timer event handler.\n if (this.enabled) {\n // Stop and start to ensure there is always only one timeout even if\n // start is called in the timer event handler.\n this.stop();\n this.start();\n }\n }\n};\n\n\n/**\n * Dispatches the TICK event. This is its own method so subclasses can override.\n */\ngoog.Timer.prototype.dispatchTick = function() {\n 'use strict';\n this.dispatchEvent(goog.Timer.TICK);\n};\n\n\n/**\n * Starts the timer.\n */\ngoog.Timer.prototype.start = function() {\n 'use strict';\n this.enabled = true;\n\n // If there is no interval already registered, start it now\n if (!this.timer_) {\n // IMPORTANT!\n // window.setInterval in FireFox has a bug - it fires based on\n // absolute time, rather than on relative time. What this means\n // is that if a computer is sleeping/hibernating for 24 hours\n // and the timer interval was configured to fire every 1000ms,\n // then after the PC wakes up the timer will fire, in rapid\n // succession, 3600*24 times.\n // This bug is described here and is already fixed, but it will\n // take time to propagate, so for now I am switching this over\n // to setTimeout logic.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\n //\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\n this.last_ = goog.now();\n }\n};\n\n\n/**\n * Stops the timer.\n */\ngoog.Timer.prototype.stop = function() {\n 'use strict';\n this.enabled = false;\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n};\n\n\n/** @override */\ngoog.Timer.prototype.disposeInternal = function() {\n 'use strict';\n goog.Timer.superClass_.disposeInternal.call(this);\n this.stop();\n delete this.timerObject_;\n};\n\n\n/**\n * Constant for the timer's event type.\n * @const\n */\ngoog.Timer.TICK = 'tick';\n\n\n/**\n * Calls the given function once, after the optional pause.\n * <p>\n * The function is always called asynchronously, even if the delay is 0. This\n * is a common trick to schedule a function to run after a batch of browser\n * event processing.\n *\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\n * or object that has a handleEvent method.\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\n * @return {number} A handle to the timer ID.\n * @template SCOPE\n */\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\n 'use strict';\n if (typeof listener === 'function') {\n if (opt_handler) {\n listener = goog.bind(listener, opt_handler);\n }\n } else if (listener && typeof listener.handleEvent == 'function') {\n // using typeof to prevent strict js warning\n listener = goog.bind(listener.handleEvent, listener);\n } else {\n throw new Error('Invalid listener argument');\n }\n\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\n // Timeouts greater than MAX_INT return immediately due to integer\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\n // schedule anything at all.\n return goog.Timer.INVALID_TIMEOUT_ID_;\n } else {\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\n }\n};\n\n\n/**\n * Clears a timeout initiated by {@link #callOnce}.\n * @param {?number} timerId A timer ID.\n */\ngoog.Timer.clear = function(timerId) {\n 'use strict';\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\n};\n\n\n/**\n * @param {number} delay Milliseconds to wait.\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\n * with which the promise will be resolved.\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\n * the specified delay, unless it is canceled first.\n * @template RESULT\n */\ngoog.Timer.promise = function(delay, opt_result) {\n 'use strict';\n var timerKey = null;\n return new goog\n .Promise(function(resolve, reject) {\n 'use strict';\n timerKey = goog.Timer.callOnce(function() {\n 'use strict';\n resolve(opt_result);\n }, delay);\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\n reject(new Error('Failed to schedule timer.'));\n }\n })\n .thenCatch(function(error) {\n 'use strict';\n // Clear the timer. The most likely reason is \"cancel\" signal.\n goog.Timer.clear(timerKey);\n throw error;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the goog.async.Throttle class.\n *\n * @see ../demos/timers.html\n */\n\ngoog.module('goog.async.Throttle');\ngoog.module.declareLegacyNamespace();\n\nconst Disposable = goog.require('goog.Disposable');\nconst Timer = goog.require('goog.Timer');\n\n\n/**\n * Throttle will perform an action that is passed in no more than once\n * per interval (specified in milliseconds). If it gets multiple signals\n * to perform the action while it is waiting, it will only perform the action\n * once at the end of the interval.\n * @final\n * @template T\n */\nclass Throttle extends Disposable {\n /**\n * @param {function(this: T, ...?)} listener Function to callback when the\n * action is triggered.\n * @param {number} interval Interval over which to throttle. The listener can\n * only be called once per interval.\n * @param {T=} handler Object in whose scope to call the listener.\n */\n constructor(listener, interval, handler) {\n super();\n /**\n * Function to callback\n * @type {function(this: T, ...?)}\n * @private\n */\n this.listener_ = handler != null ? listener.bind(handler) : listener;\n\n /**\n * Interval for the throttle time\n * @type {number}\n * @private\n */\n this.interval_ = interval;\n\n /**\n * The last arguments passed into `fire`, or null if there is no pending\n * call.\n * @private {?IArrayLike}\n */\n this.args_ = null;\n\n /**\n * Indicates that the action is pending and needs to be fired.\n * @type {boolean}\n * @private\n */\n this.shouldFire_ = false;\n\n /**\n * Indicates the count of nested pauses currently in effect on the throttle.\n * When this count is not zero, fired actions will be postponed until the\n * throttle is resumed enough times to drop the pause count to zero.\n * @type {number}\n * @private\n */\n this.pauseCount_ = 0;\n\n /**\n * Timer for scheduling the next callback\n * @type {?number}\n * @private\n */\n this.timer_ = null;\n }\n\n /**\n * Notifies the throttle that the action has happened. It will throttle\n * the call so that the callback is not called too often according to the\n * interval parameter passed to the constructor, passing the arguments\n * from the last call of this function into the throttled function.\n * @param {...?} var_args Arguments to pass on to the throttled function.\n */\n fire(var_args) {\n this.args_ = arguments;\n if (!this.timer_ && !this.pauseCount_) {\n this.doAction_();\n } else {\n this.shouldFire_ = true;\n }\n }\n\n /**\n * Cancels any pending action callback. The throttle can be restarted by\n * calling {@link #fire}.\n */\n stop() {\n if (this.timer_) {\n Timer.clear(this.timer_);\n this.timer_ = null;\n this.shouldFire_ = false;\n this.args_ = null;\n }\n }\n\n /**\n * Pauses the throttle. All pending and future action callbacks will be\n * delayed until the throttle is resumed. Pauses can be nested.\n */\n pause() {\n this.pauseCount_++;\n }\n\n /**\n * Resumes the throttle. If doing so drops the pausing count to zero,\n * pending action callbacks will be executed as soon as possible, but\n * still no sooner than an interval's delay after the previous call.\n * Future action callbacks will be executed as normal.\n */\n resume() {\n this.pauseCount_--;\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /** @override */\n disposeInternal() {\n super.disposeInternal();\n this.stop();\n }\n\n /**\n * Handler for the timer to fire the throttle\n * @private\n */\n onTimer_() {\n this.timer_ = null;\n\n if (this.shouldFire_ && !this.pauseCount_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /**\n * Calls the callback\n * @private\n */\n doAction_() {\n this.timer_ = Timer.callOnce(() => this.onTimer_(), this.interval_);\n const args = this.args_;\n // release memory first so it always happens even if listener throws\n this.args_ = null;\n this.listener_.apply(null, args);\n }\n}\n\nexports = Throttle;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class to create objects which want to handle multiple events\n * and have their listeners easily cleaned up via a dispose method.\n *\n * Example:\n * <pre>\n * function Something() {\n * Something.base(this);\n *\n * ... set up object ...\n *\n * // Add event listeners\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\n * }\n * goog.inherits(Something, goog.events.EventHandler);\n *\n * Something.prototype.disposeInternal = function() {\n * Something.base(this, 'disposeInternal');\n * goog.dom.removeNode(this.container);\n * };\n *\n *\n * // Then elsewhere:\n *\n * var activeSomething = null;\n * function openSomething() {\n * activeSomething = new Something();\n * }\n *\n * function closeSomething() {\n * if (activeSomething) {\n * activeSomething.dispose(); // Remove event listeners\n * activeSomething = null;\n * }\n * }\n * </pre>\n */\n\ngoog.provide('goog.events.EventHandler');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.events');\ngoog.require('goog.object');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventTarget');\ngoog.requireType('goog.events.EventWrapper');\n\n\n\n/**\n * Super class for objects that want to easily manage a number of event\n * listeners. It allows a short cut to listen and also provides a quick way\n * to remove all events listeners belonging to this object.\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\n * @constructor\n * @extends {goog.Disposable}\n * @template SCOPE\n */\ngoog.events.EventHandler = function(opt_scope) {\n 'use strict';\n goog.Disposable.call(this);\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\n // that access this private variable. :(\n this.handler_ = opt_scope;\n\n /**\n * Keys for events that are being listened to.\n * @type {!Object<!goog.events.Key>}\n * @private\n */\n this.keys_ = {};\n};\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\n\n\n/**\n * Utility array used to unify the cases of listening for an array of types\n * and listening for a single event, without using recursion or allocating\n * an array each time.\n * @type {!Array<string>}\n * @const\n * @private\n */\ngoog.events.EventHandler.typeArray_ = [];\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listen = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listen_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|!AddEventListenerOptions|undefined} options\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenWithScope = function(\n src, type, fn, options, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listen_(src, type, fn, options, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listen_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (!Array.isArray(type)) {\n if (type) {\n goog.events.EventHandler.typeArray_[0] = type.toString();\n }\n type = goog.events.EventHandler.typeArray_;\n }\n for (var i = 0; i < type.length; i++) {\n var listenerObj = goog.events.listen(\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\n opt_scope || self.handler_ || self);\n\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnce = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listenOnce_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\n src, type, fn, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenOnce_(src, type, fn, capture, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired\n * the event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenOnce_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var listenerObj = goog.events.listenOnce(\n src, type, opt_fn || self.handleEvent, opt_options,\n opt_scope || self.handler_ || self);\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\n src, wrapper, listener, opt_capt) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Remove the opt_scope from this function and then\n // templatize it.\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\n * listener Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\n src, wrapper, listener, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\n * method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.listen(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * @return {number} Number of listeners registered by this handler.\n */\ngoog.events.EventHandler.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var key in this.keys_) {\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\n count++;\n }\n }\n return count;\n};\n\n\n/**\n * Unlistens on an event.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.unlisten = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n var listener = goog.events.getListener(\n src, type, opt_fn || self.handleEvent, capture,\n opt_scope || self.handler_ || self);\n\n if (listener) {\n goog.events.unlistenByKey(listener);\n delete self.keys_[listener.key];\n }\n }\n\n return self;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.EventTarget} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.unlisten(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * Unlistens to all events.\n */\ngoog.events.EventHandler.prototype.removeAll = function() {\n 'use strict';\n goog.object.forEach(this.keys_, function(listenerObj, key) {\n 'use strict';\n if (this.keys_.hasOwnProperty(key)) {\n goog.events.unlistenByKey(listenerObj);\n }\n }, this);\n\n this.keys_ = {};\n};\n\n\n/**\n * Disposes of this EventHandler and removes all listeners that it registered.\n * @override\n * @protected\n */\ngoog.events.EventHandler.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\n this.removeAll();\n};\n\n\n/**\n * Default event handler\n * @param {goog.events.Event} e Event object.\n */\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\n 'use strict';\n throw new Error('EventHandler.handleEvent not implemented');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a utility for tracing and debugging WebChannel\n * requests.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.require('goog.json');\ngoog.require('goog.log');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.net.XmlHttp.ReadyState');\n\n\n\n/**\n * Logs and keeps a buffer of debugging info for the Channel.\n *\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.WebChannelDebug = function() {\n 'use strict';\n /**\n * The logger instance.\n * @const\n * @private {?goog.log.Logger}\n */\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\n\n /**\n * Whether to enable redact. Defaults to true.\n * @private {boolean}\n */\n this.redactEnabled_ = true;\n};\n\n\ngoog.scope(function() {\n'use strict';\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Turns off redact.\n */\nWebChannelDebug.prototype.disableRedact = function() {\n 'use strict';\n this.redactEnabled_ = false;\n};\n\n\n/**\n * Logs that the browser went offline during the lifetime of a request.\n * @param {goog.Uri} url The URL being requested.\n */\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'BROWSER_OFFLINE: ' + url;\n });\n};\n\n\n/**\n * Logs an XmlHttp request..\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {?string} postData The data posted in the request.\n */\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\n verb, uri, id, attempt, postData) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\n });\n};\n\n\n/**\n * Logs the meta data received from an XmlHttp request.\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\n * @param {number} statusCode The HTTP status code.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\n verb, uri, id, attempt, readyState, statusCode) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\n });\n};\n\n\n/**\n * Logs the response data received from an XmlHttp request.\n * @param {string|number|undefined} id The request id.\n * @param {?string} responseText The response text.\n * @param {?string=} opt_desc Optional request description.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\n id, responseText, opt_desc) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\n (opt_desc ? ' ' + opt_desc : '');\n });\n};\n\n\n/**\n * Logs a request timeout.\n * @param {goog.Uri} uri The uri that timed out.\n */\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'TIMEOUT: ' + uri;\n });\n};\n\n\n/**\n * Logs a debug message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.debug = function(text) {\n 'use strict';\n goog.log.fine(this.logger_, text);\n};\n\n\n/**\n * Logs an exception\n * @param {Error} e The error or error event.\n * @param {goog.log.Loggable=} opt_msg The optional message,\n * defaults to 'Exception'.\n */\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\n 'use strict';\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\n};\n\n\n/**\n * Logs an info message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.info = function(text) {\n 'use strict';\n goog.log.info(this.logger_, text);\n};\n\n\n/**\n * Logs a warning message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.warning = function(text) {\n 'use strict';\n goog.log.warning(this.logger_, text);\n};\n\n\n/**\n * Logs a severe message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.severe = function(text) {\n 'use strict';\n goog.log.error(this.logger_, text);\n};\n\n\n/**\n * Removes potentially private data from a response so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} responseText A JSON response to clean.\n * @return {?string} The cleaned response.\n * @private\n */\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\n 'use strict';\n if (!this.redactEnabled_) {\n return responseText;\n }\n\n if (!responseText) {\n return null;\n }\n\n try {\n var responseArray = JSON.parse(responseText);\n if (responseArray) {\n for (var i = 0; i < responseArray.length; i++) {\n if (Array.isArray(responseArray[i])) {\n this.maybeRedactArray_(responseArray[i]);\n }\n }\n }\n\n return goog.json.serialize(responseArray);\n } catch (e) {\n this.debug('Exception parsing expected JS array - probably was not JS');\n return responseText;\n }\n};\n\n\n/**\n * Removes data from a response array that may be sensitive.\n * @param {!Array<?>} array The array to clean.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\n 'use strict';\n if (array.length < 2) {\n return;\n }\n var dataPart = array[1];\n if (!Array.isArray(dataPart)) {\n return;\n }\n if (dataPart.length < 1) {\n return;\n }\n\n var type = dataPart[0];\n if (type != 'noop' && type != 'stop' && type != 'close') {\n // redact all fields in the array\n for (var i = 1; i < dataPart.length; i++) {\n dataPart[i] = '';\n }\n }\n};\n\n\n/**\n * Removes potentially private data from a request POST body so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} data The data string to clean.\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\n 'use strict';\n if (!this.redactEnabled_) {\n return data;\n }\n\n if (!data) {\n return null;\n }\n var out = '';\n var params = data.split('&');\n for (var i = 0; i < params.length; i++) {\n var param = params[i];\n var keyValue = param.split('=');\n if (keyValue.length > 1) {\n var key = keyValue[0];\n var value = keyValue[1];\n\n var keyParts = key.split('_');\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\n out += key + '=' + value + '&';\n } else {\n out += key + '=' +\n 'redacted' +\n '&';\n }\n }\n }\n return out;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Static utilities for collecting stats associated with\n * ChannelRequest.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.requestStats');\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\n\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\n\n\ngoog.scope(function() {\n'use strict';\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\n\n/**\n * Events fired.\n * @const\n */\nrequestStats.Event = {};\n\n\n/**\n * Singleton event target for firing stat events\n * @type {?goog.events.EventTarget}\n * @private\n */\nrequestStats.eventTarget_ = null;\n\n/**\n * Singleton event target for firing stat events\n * @return {!goog.events.EventTarget}\n * @private\n */\nrequestStats.getStatEventTarget_ = function() {\n 'use strict';\n requestStats.eventTarget_ =\n requestStats.eventTarget_ || new goog.events.EventTarget();\n return requestStats.eventTarget_;\n};\n\n/**\n * The type of event that occurs every time some information about how reachable\n * the server is is discovered.\n */\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\n\n\n/**\n * Types of events which reveal information about the reachability of the\n * server.\n * @enum {number}\n */\nrequestStats.ServerReachability = {\n REQUEST_MADE: 1,\n REQUEST_SUCCEEDED: 2,\n REQUEST_FAILED: 3,\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\n};\n\n\n\n/**\n * Event class for SERVER_REACHABILITY_EVENT.\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\n 'use strict';\n goog.events.Event.call(\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\n\n /**\n * @type {requestStats.ServerReachability}\n */\n this.reachabilityType = reachabilityType;\n};\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\n\n\n/**\n * Notify the channel that a particular fine grained network event has occurred.\n * Should be considered package-private.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n */\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\n};\n\n\n/**\n * Stat Event that fires when things of interest happen that may be useful for\n * applications to know about for stats or debugging purposes.\n */\nrequestStats.Event.STAT_EVENT = 'statevent';\n\n\n/**\n * Enum that identifies events for statistics that are interesting to track.\n * @enum {number}\n */\nrequestStats.Stat = {\n /** Event indicating a new connection attempt. */\n CONNECT_ATTEMPT: 0,\n\n /** Event indicating a connection error due to a general network problem. */\n ERROR_NETWORK: 1,\n\n /**\n * Event indicating a connection error that isn't due to a general network\n * problem.\n */\n ERROR_OTHER: 2,\n\n /** Event indicating the start of test stage one. */\n TEST_STAGE_ONE_START: 3,\n\n /** Event indicating the start of test stage two. */\n TEST_STAGE_TWO_START: 4,\n\n /** Event indicating the first piece of test data was received. */\n TEST_STAGE_TWO_DATA_ONE: 5,\n\n /**\n * Event indicating that the second piece of test data was received and it was\n * received separately from the first.\n */\n TEST_STAGE_TWO_DATA_TWO: 6,\n\n /** Event indicating both pieces of test data were received simultaneously. */\n TEST_STAGE_TWO_DATA_BOTH: 7,\n\n /** Event indicating stage one of the test request failed. */\n TEST_STAGE_ONE_FAILED: 8,\n\n /** Event indicating stage two of the test request failed. */\n TEST_STAGE_TWO_FAILED: 9,\n\n /**\n * Event indicating that a buffering proxy is likely between the client and\n * the server.\n */\n PROXY: 10,\n\n /**\n * Event indicating that no buffering proxy is likely between the client and\n * the server.\n */\n NOPROXY: 11,\n\n /** Event indicating an unknown SID error. */\n REQUEST_UNKNOWN_SESSION_ID: 12,\n\n /** Event indicating a bad status code was received. */\n REQUEST_BAD_STATUS: 13,\n\n /** Event indicating incomplete data was received */\n REQUEST_INCOMPLETE_DATA: 14,\n\n /** Event indicating bad data was received */\n REQUEST_BAD_DATA: 15,\n\n /** Event indicating no data was received when data was expected. */\n REQUEST_NO_DATA: 16,\n\n /** Event indicating a request timeout. */\n REQUEST_TIMEOUT: 17,\n\n /**\n * Event indicating that the server never received our hanging GET and so it\n * is being retried.\n */\n BACKCHANNEL_MISSING: 18,\n\n /**\n * Event indicating that we have determined that our hanging GET is not\n * receiving data when it should be. Thus it is dead dead and will be retried.\n */\n BACKCHANNEL_DEAD: 19,\n\n /**\n * The browser declared itself offline during the lifetime of a request, or\n * was offline when a request was initially made.\n */\n BROWSER_OFFLINE: 20\n};\n\n\n\n/**\n * Event class for STAT_EVENT.\n *\n * @param {goog.events.EventTarget} eventTarget The stat event target for\n the channel.\n * @param {requestStats.Stat} stat The stat.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.StatEvent = function(eventTarget, stat) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\n\n /**\n * The stat\n * @type {requestStats.Stat}\n */\n this.stat = stat;\n};\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\n\n\n/**\n * Returns the singleton event target for stat events.\n * @return {!goog.events.EventTarget} The event target for stat events.\n */\nrequestStats.getStatEventTarget = function() {\n 'use strict';\n return requestStats.getStatEventTarget_();\n};\n\n\n/**\n * Helper function to call the stat event callback.\n * @param {requestStats.Stat} stat The stat.\n */\nrequestStats.notifyStatEvent = function(stat) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\n};\n\n\n/**\n * An event that fires when POST requests complete successfully, indicating\n * the size of the POST and the round trip time.\n */\nrequestStats.Event.TIMING_EVENT = 'timingevent';\n\n\n\n/**\n * Event class for requestStats.Event.TIMING_EVENT\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {number} size The number of characters in the POST data.\n * @param {number} rtt The total round trip time from POST to response in MS.\n * @param {number} retries The number of times the POST had to be retried.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\n\n /**\n * @type {number}\n */\n this.size = size;\n\n /**\n * @type {number}\n */\n this.rtt = rtt;\n\n /**\n * @type {number}\n */\n this.retries = retries;\n};\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\n\n\n/**\n * Helper function to notify listeners about POST request performance.\n *\n * @param {number} size Number of characters in the POST data.\n * @param {number} rtt The amount of time from POST start to response.\n * @param {number} retries The number of times the POST had to be retried.\n */\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.TimingEvent(target, size, rtt, retries));\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * starts processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} startHook The function for the start hook.\n */\nrequestStats.setStartThreadExecutionHook = function(startHook) {\n 'use strict';\n requestStats.startExecutionHook_ = startHook;\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * stops processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} endHook The function for the end hook.\n */\nrequestStats.setEndThreadExecutionHook = function(endHook) {\n 'use strict';\n requestStats.endExecutionHook_ = endHook;\n};\n\n\n/**\n * Application provided execution hook for the start hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.startExecutionHook_ = function() {};\n\n\n/**\n * Application provided execution hook for the end hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.endExecutionHook_ = function() {};\n\n\n/**\n * Helper function to call the start hook\n */\nrequestStats.onStartExecution = function() {\n 'use strict';\n requestStats.startExecutionHook_();\n};\n\n\n/**\n * Helper function to call the end hook\n */\nrequestStats.onEndExecution = function() {\n 'use strict';\n requestStats.endExecutionHook_();\n};\n\n\n/**\n * Wrapper around SafeTimeout which calls the start and end execution hooks\n * with a try...finally block.\n * @param {Function} fn The callback function.\n * @param {number} ms The time in MS for the timer.\n * @return {number} The ID of the timer.\n */\nrequestStats.setTimeout = function(fn, ms) {\n 'use strict';\n if (typeof fn !== 'function') {\n throw new Error('Fn must not be null and must be a function');\n }\n return goog.global.setTimeout(function() {\n 'use strict';\n requestStats.onStartExecution();\n try {\n fn();\n } finally {\n requestStats.onEndExecution();\n }\n }, ms);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Error codes shared between goog.net.IframeIo and\n * goog.net.XhrIo.\n */\n\ngoog.provide('goog.net.ErrorCode');\n\n\n/**\n * Error codes\n * @enum {number}\n */\ngoog.net.ErrorCode = {\n\n /**\n * There is no error condition.\n */\n NO_ERROR: 0,\n\n /**\n * The most common error from iframeio, unfortunately, is that the browser\n * responded with an error page that is classed as a different domain. The\n * situations, are when a browser error page is shown -- 404, access denied,\n * DNS failure, connection reset etc.)\n *\n */\n ACCESS_DENIED: 1,\n\n /**\n * Currently the only case where file not found will be caused is when the\n * code is running on the local file system and a non-IE browser makes a\n * request to a file that doesn't exist.\n */\n FILE_NOT_FOUND: 2,\n\n /**\n * If Firefox shows a browser error page, such as a connection reset by\n * server or access denied, then it will fail silently without the error or\n * load handlers firing.\n */\n FF_SILENT_ERROR: 3,\n\n /**\n * Custom error provided by the client through the error check hook.\n */\n CUSTOM_ERROR: 4,\n\n /**\n * Exception was thrown while processing the request.\n */\n EXCEPTION: 5,\n\n /**\n * The Http response returned a non-successful http status code.\n */\n HTTP_ERROR: 6,\n\n /**\n * The request was aborted.\n */\n ABORT: 7,\n\n /**\n * The request timed out.\n */\n TIMEOUT: 8,\n\n /**\n * The resource is not available offline.\n */\n OFFLINE: 9,\n};\n\n\n/**\n * Returns a friendly error message for an error code. These messages are for\n * debugging and are not localized.\n * @param {goog.net.ErrorCode} errorCode An error code.\n * @return {string} A message for debugging.\n */\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\n 'use strict';\n switch (errorCode) {\n case goog.net.ErrorCode.NO_ERROR:\n return 'No Error';\n\n case goog.net.ErrorCode.ACCESS_DENIED:\n return 'Access denied to content document';\n\n case goog.net.ErrorCode.FILE_NOT_FOUND:\n return 'File not found';\n\n case goog.net.ErrorCode.FF_SILENT_ERROR:\n return 'Firefox silently errored';\n\n case goog.net.ErrorCode.CUSTOM_ERROR:\n return 'Application custom error';\n\n case goog.net.ErrorCode.EXCEPTION:\n return 'An exception occurred';\n\n case goog.net.ErrorCode.HTTP_ERROR:\n return 'Http response at 400 or 500 level';\n\n case goog.net.ErrorCode.ABORT:\n return 'Request was aborted';\n\n case goog.net.ErrorCode.TIMEOUT:\n return 'Request timed out';\n\n case goog.net.ErrorCode.OFFLINE:\n return 'The resource is not available offline';\n\n default:\n return 'Unrecognized error code';\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Common events for the network classes.\n */\n\n\ngoog.provide('goog.net.EventType');\n\n\n/**\n * Event names for network events\n * @enum {string}\n */\ngoog.net.EventType = {\n COMPLETE: 'complete',\n SUCCESS: 'success',\n ERROR: 'error',\n ABORT: 'abort',\n READY: 'ready',\n READY_STATE_CHANGE: 'readystatechange',\n TIMEOUT: 'timeout',\n INCREMENTAL_DATA: 'incrementaldata',\n PROGRESS: 'progress',\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\n // goog.net.XhrIo to allow binding listeners specific to each type of\n // progress.\n DOWNLOAD_PROGRESS: 'downloadprogress',\n UPLOAD_PROGRESS: 'uploadprogress',\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\n * and metadata about them.\n */\n\ngoog.provide('goog.net.XmlHttpFactory');\n\n/** @suppress {extraRequire} Typedef. */\ngoog.require('goog.net.XhrLike');\n\n\n\n/**\n * Abstract base class for an XmlHttpRequest factory.\n * @constructor\n */\ngoog.net.XmlHttpFactory = function() {};\n\n\n/**\n * Cache of options - we only actually call internalGetOptions once.\n * @type {?Object}\n * @private\n */\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\n\n\n/**\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\n */\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\n\n\n/**\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n */\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\n 'use strict';\n return this.cachedOptions_ ||\n (this.cachedOptions_ = this.internalGetOptions());\n};\n\n\n/**\n * Override this method in subclasses to preserve the caching offered by\n * getOptions().\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n * @protected\n */\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The API spec for the WebChannel messaging library.\n *\n * Similar to HTML5 WebSocket, WebChannel offers an abstraction for\n * point-to-point socket-like communication between a browser client and\n * a remote origin.\n *\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\n * may be multiplexed over the same WebChannelTransport, which encapsulates\n * the underlying physical connectivity over standard wire protocols\n * such as HTTP.\n *\n * A WebChannel in turn represents a logical communication channel between\n * the client and server endpoint. A WebChannel remains open for as long\n * as the client or server endpoint allows.\n *\n * Messages are delivered in-order and reliably over the same WebChannel,\n * and the choice of the underlying wire protocols is completely transparent\n * to the API users.\n *\n * Note that we have no immediate plan to move this API out of labs. While\n * the implementation is production ready, the API is subject to change.\n */\n\ngoog.provide('goog.net.WebChannel');\ngoog.provide('goog.net.WebChannel.Options');\n\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * A WebChannel represents a logical bi-directional channel over which the\n * client communicates with a remote server that holds the other endpoint\n * of the channel. A WebChannel is always created in the context of a shared\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\n * and server-side implementations to decide how or when multiplexing is\n * to be enabled.\n *\n * @interface\n * @extends {goog.events.Listenable}\n */\ngoog.net.WebChannel = function() {};\n\n\n\n/**\n * This interface defines a pluggable API to allow WebChannel runtime to support\n * customized algorithms in order to recover from transient failures such as\n * those failures caused by network or proxies (intermediaries).\n *\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\n * offline mode.\n *\n * Extra measurements and logging could also be implemented in the custom\n * module, which has the full knowledge of all the state transitions\n * (due to failures).\n *\n * A default algorithm will be provided by the webchannel library itself. Custom\n * algorithms are expected to be tailored to specific client platforms or\n * networking environments, e.g. mobile, cellular network.\n *\n * @interface\n */\ngoog.net.WebChannel.FailureRecovery = function() {};\n\n\n/**\n * Configuration spec for newly created WebChannel instances.\n *\n * WebChannels are configured in the context of the containing\n * {@link WebChannelTransport}. The configuration parameters are specified\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\n * @record\n */\ngoog.net.WebChannel.Options = function() {};\n\n/**\n * Transport-metadata support.\n *\n * Custom HTTP headers to be added to every message sent to the\n * server. This object is mutable, and custom headers may be changed, removed,\n * or added during the runtime after a channel has been opened.\n *\n * Custom headers may trigger CORS preflight. See other related options.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageHeaders;\n\n/**\n * Transport-metadata support.\n *\n * Similar to messageHeaders, but any custom HTTP headers will\n * be sent only once when the channel is opened as part of the handshae request.\n * Typical usage is to send an auth header to the server, which only checks\n * the auth header at the time during the handshake when the channel is opened.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.initMessageHeaders;\n\n/**\n * Sent as initMessageHeaders via X-WebChannel-Content-Type,\n * to inform the server the MIME type of WebChannel messages.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageContentType;\n\n/**\n * Transport-metadata support.\n *\n * Custom url query parameters to be added to every message\n * sent to the server. This object is mutable, and custom parameters may be\n * changed, removed or added during the runtime after a channel has been opened.\n *\n * TODO: initMessageUrlParams\n * TODO: closeMessageUrlParams (custom url query params to be added to the\n * channel-close message. Custom headers are not supported due to the use of\n * SendBeacon)\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageUrlParams;\n\n/**\n * Whether a special header should be added to\n * each message so that the server can dispatch webchannel messages without\n * knowing the URL path prefix. Defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProtocolHeaderRequired;\n\n/**\n * The maximum number of in-flight HTTP requests allowed\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\n * will have no effect.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.concurrentRequestLimit;\n\n/**\n * Setting this to true to allow the use of sub-domains\n * (as configured by the server) to send XHRs with the CORS withCredentials\n * bit set to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.supportsCrossDomainXhr;\n\n/**\n * Whether to bypass v8 encoding of client-sent messages.\n * This defaults to false now due to legacy servers. New applications should\n * always configure this option to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.sendRawJson;\n\n/**\n * The URL parameter name that contains the session id (for sticky routing of\n * HTTP requests). When this param is specified, a server that supports this\n * option will respond with an opaque session id as part of the initial\n * handshake (via the X-HTTP-Session-Id header); and all the subsequent requests\n * will contain the httpSessionIdParam. This option will take precedence over\n * any duplicated parameter specified with messageUrlParams, whose value will be\n * ignored.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpSessionIdParam;\n\n/**\n * The URL parameter name to allow custom HTTP\n * headers to be overwritten as a URL param to bypass CORS preflight.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpHeadersOverwriteParam;\n\n/**\n * Whether to encode Options.initMessageHeaders in the HTTP request body.\n * This option defaults to false. If true, Options.httpHeadersOverwriteParam\n * will be ignored.\n *\n * This option should not be set if Options.fastHandshake is set (which\n * uses GET for handshake).\n *\n * Web-only feature.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.encodeInitMessageHeaders;\n\n/**\n * Whether to force long-polling from client to server.\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\n * is buffering data sent by the server.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.forceLongPolling;\n\n/**\n * Whether to enable automatic detection of buffering proxies. In the presence\n * of any buffering proxy, webchannel will use long-polling to send messages\n * from the server to the client. This option defaults to false.\n * Currently when fastHandshake is enabled, this option will be ignored.\n * Compared to \"forceLongPolling\", this option may introduce up to 2-RTT\n * extra latency for delivering messages generated immediately after the\n * handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.detectBufferingProxy;\n\n/**\n * Enable true 0-RTT message delivery, including\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\n * defaults to false. Note it is allowed to send messages before Open event is\n * received, after a channel has been opened. In order to enable 0-RTT,\n * messages will be encoded as part of URL and therefore there needs be a size\n * limit for those initial messages that are sent immediately as part of the\n * GET handshake request. With sendRawJson=true, this limit is currently set\n * to 4K chars and data beyond this limit will be buffered till the handshake\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\n * to limit the amount of data that is sent as part of the handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.fastHandshake;\n\n/**\n * Enable the blocking RPC semantics for the handshake:\n * 1) the completion of handshake is blocked by the server-side application\n * logic for handling the handshake (HTTP) request; 2) the client application\n * will inspect the handshake (HTTP) response headers as generated\n * by the server application (v.s. by only the webchannel runtime). This option\n * defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.blockingHandshake;\n\n/**\n * Whether to disable logging redact. By default, redact is\n * enabled to remove any message payload or user-provided info\n * from closure logs.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.disableRedact;\n\n/**\n * Inform the server about the client profile to enable\n * customized configs that are optimized for certain clients or environments.\n * Currently this information is sent via X-WebChannel-Client-Profile header.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProfile;\n\n/**\n * The internal channel parameter name to allow\n * experimental channel configurations. Supported options include fastfail,\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\n * change.\n * @type {!Object<string, boolean|number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.internalChannelParams;\n\n/**\n * Allows the caller to override the factory used to create\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\n * @type {!goog.net.XmlHttpFactory|undefined}\n */\ngoog.net.WebChannel.Options.prototype.xmlHttpFactory;\n\n/**\n * Client-side thresholds that decide when to refresh\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\n * or compression context. The client-side thresholds should be significantly\n * smaller than the server-side thresholds. This allows the client to eliminate\n * any latency introduced by request refreshing, i.e. an RTT window during which\n * messages may be buffered on the server-side. Supported params include\n * totalBytesReceived, totalDurationMs.\n * @type {!Object<string, number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.requestRefreshThresholds;\n\n/**\n * This is an experimental feature to use WHATWG Fetch/streams (when supported)\n * for the backchannel. If a custom 'xmlHttpFactory' is speficied, this option\n * will not be effective. This option defaults to false now and will eventually\n * be turned on by default.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.useFetchStreams;\n\n/**\n * Opt-in to enable Chrome origin trials from the WebChannel client. See\n * https://github.com/GoogleChrome/OriginTrials\n *\n * Origin trial history:\n * - fetch upload (11/2020 - 07/2021)\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * Participating in the origin trials will help Chrome to release new Web\n * platform features sooner, which will in turn help improve WebChannel\n * performance.\n *\n * Origin trials are not expected to interfere with WebChannel wire messages\n * and should not introduce any noticeable overhead.\n *\n * This is enabled by default with any on-going origin-trial.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.enableOriginTrials;\n\n\n/**\n * Types that are allowed as message data.\n *\n * Note that JS objects (sent by the client) can only have string encoded\n * values due to the limitation of the current wire protocol.\n *\n * Unicode strings (sent by the server) may or may not need be escaped, as\n * decided by the server.\n *\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\n */\ngoog.net.WebChannel.MessageData;\n\n\n/**\n * Open the WebChannel against the URI specified in the constructor.\n */\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\n\n\n/**\n * Close the WebChannel.\n *\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\n * to any in-flight messages sent to the server.\n *\n * If you need such a guarantee, see the Half the halfClose() method.\n */\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\n\n\n/**\n * Half-close the WebChannel.\n *\n * Half-close semantics:\n * 1. delivered as a regular message in FIFO programming order\n * 2. the server is expected to return a half-close too (with or without\n * application involved), which will trigger a full close (shutdown)\n * on the client side\n * 3. for now, the half-close event defined for server-initiated\n * half-close is not exposed to the client application\n * 4. a client-side half-close may be triggered internally when the client\n * receives a half-close from the server; and the client is expected to\n * do a full close after the half-close is acked and delivered\n * on the server-side.\n * 5. Full close is always a forced one. See the close() method.\n *\n * New messages sent after halfClose() will be dropped.\n *\n * NOTE: This is not yet implemented, and will throw an exception if called.\n */\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\n\n\n/**\n * Sends a message to the server that maintains the other endpoint of\n * the WebChannel.\n *\n * O-RTT behavior:\n * 1. messages sent before open() is called will always be delivered as\n * part of the handshake, i.e. with 0-RTT\n * 2. messages sent after open() is called but before the OPEN event\n * is received will be delivered as part of the handshake if\n * send() is called from the same execution context as open().\n * 3. otherwise, those messages will be buffered till the handshake\n * is completed (which will fire the OPEN event).\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n */\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\n\n\n/**\n * Common events fired by WebChannels.\n * @enum {string}\n */\ngoog.net.WebChannel.EventType = {\n /** Dispatched when the channel is opened. */\n OPEN: goog.events.getUniqueId('open'),\n\n /** Dispatched when the channel is closed. */\n CLOSE: goog.events.getUniqueId('close'),\n\n /**\n * Dispatched when the channel is aborted due to errors.\n *\n * For backward compatibility reasons, a CLOSE event will also be\n * dispatched, following the ERROR event, which indicates that the channel\n * has been completely shutdown .\n */\n ERROR: goog.events.getUniqueId('error'),\n\n /** Dispatched when the channel has received a new message. */\n MESSAGE: goog.events.getUniqueId('message')\n};\n\n\n\n/**\n * The event interface for the MESSAGE event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.MessageEvent = function() {\n 'use strict';\n goog.net.WebChannel.MessageEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\n};\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\n\n\n/**\n * The content of the message received from the server.\n *\n * @type {!goog.net.WebChannel.MessageData}\n */\ngoog.net.WebChannel.MessageEvent.prototype.data;\n\n\n/**\n * The metadata key when the MESSAGE event represents a metadata message.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\n\n\n/**\n * Metadata as HTTP status code. Typically sent before the channel is\n * half-closed by the server. To be implemented.\n *\n * @type {number|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.statusCode;\n\n\n/**\n * Metadata as HTTP headers. Typically sent before the channel is\n * half-closed by the server. To be implemented.\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.responseHeaders;\n\n\n/**\n * WebChannel level error conditions.\n *\n * Summary of error debugging and reporting in WebChannel:\n *\n * Network Error\n * 1. By default the webchannel library will set the error status to\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\n * may be recovered by the application by retrying and opening a new channel.\n * 2. There may be lost messages (not acked by the server) when a channel is\n * aborted. Currently we don't have a public API to retrieve messages that\n * are waiting to be acked on the client side. File a bug if you think it\n * is useful to expose such an API.\n * 3. Details of why a channel fails are available via closure debug logs,\n * and stats events (see webchannel/requeststats.js). Those are internal\n * stats and are subject to change. File a bug if you think it's useful to\n * version and expose such stats as part of the WebChannel API.\n *\n * Server Error\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\n * when auth fails.\n * 2. We don't currently generate any such errors, because most of the time\n * it's the responsibility of upper-layer frameworks or the application\n * itself to indicate to the client why a webchannel has been failed\n * by the server.\n * 3. When a channel is failed by the server explicitly, we still signal\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\n * server does a fail-over, or becomes overloaded, or conducts a forced\n * shutdown etc.\n * 4. We use some heuristic to decide if the network (aka cloud) is down\n * v.s. the actual server is down.\n *\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\n * the client to indicate the HTTP response status code of the last HTTP\n * request initiated by the WebChannel client library, for debugging\n * purposes only.\n *\n * See WebChannel.Options.backChannelFailureRecovery and\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\n *\n * @enum {number}\n */\ngoog.net.WebChannel.ErrorStatus = {\n /** No error has occurred. */\n OK: 0,\n\n /** Communication to the server has failed. */\n NETWORK_ERROR: 1,\n\n /** The server fails to accept or process the WebChannel. */\n SERVER_ERROR: 2\n};\n\n\n\n/**\n * The event interface for the ERROR event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.ErrorEvent = function() {\n 'use strict';\n goog.net.WebChannel.ErrorEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\n};\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\n\n\n/**\n * The error status.\n *\n * @type {!goog.net.WebChannel.ErrorStatus}\n */\ngoog.net.WebChannel.ErrorEvent.prototype.status;\n\n\n/**\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\n * of the WebChannel instance.\n */\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\n\n\n\n/**\n * The runtime properties of the WebChannel instance.\n *\n * This class is defined for debugging and monitoring purposes, as well as for\n * runtime functions that the application may choose to manage by itself.\n *\n * @interface\n */\ngoog.net.WebChannel.RuntimeProperties = function() {};\n\n\n/**\n * @return {number} The effective limit for the number of concurrent HTTP\n * requests that are allowed to be made for sending messages from the client\n * to the server. When SPDY is not enabled, this limit will be one.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\n goog.abstractMethod;\n\n\n/**\n * For applications that need support multiple channels (e.g. from\n * different tabs) to the same origin, use this method to decide if SPDY is\n * enabled and therefore it is safe to open multiple channels.\n *\n * If SPDY is disabled, the application may choose to limit the number of active\n * channels to one or use other means such as sub-domains to work around\n * the browser connection limit.\n *\n * @return {boolean} Whether SPDY is enabled for the origin against which\n * the channel is created.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\n goog.abstractMethod;\n\n\n/**\n * @return {number} The number of requests (for sending messages to the server)\n * that are pending. If this number is approaching the value of\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\n * a higher latency.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\n goog.abstractMethod;\n\n\n/**\n * For applications to query the current HTTP session id, sent by the server\n * during the initial handshake.\n *\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method generates an in-band commit request to the server, which will\n * ack the commit request as soon as all messages sent prior to this commit\n * request have been committed by the application.\n *\n * Committing a message has a stronger semantics than delivering a message\n * to the application. Detail spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Timeout or cancellation is not supported and the application is expected to\n * abort the channel if the commit-ack fails to arrive in time.\n *\n * ===\n *\n * This is currently implemented only in the client layer and the commit\n * callback will be invoked after all the pending client-sent messages have been\n * delivered by the server-side webchannel endpoint. This semantics is\n * different and weaker than what's required for end-to-end ack which requires\n * the server application to ack the in-order delivery of messages that are sent\n * before the commit request is issued.\n *\n * Commit should only be called after the channel open event is received.\n * Duplicated commits are allowed and only the last callback is guaranteed.\n * Commit called after the channel has been closed will be ignored.\n *\n * @param {function()} callback The callback will be invoked once an\n * ack has been received for the current commit or any newly issued commit.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\n\n\n/**\n * This method may be used by the application to recover from a peer failure\n * or to enable sender-initiated flow-control.\n *\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Note that the caller should NOT modify the list of returned messages.\n *\n * @return {!Array<!goog.net.WebChannel.MessageData>} The list of messages that\n * have not received commit-ack from the server; or if no commit has been\n * issued, the list of messages that have not been delivered to the server\n * application.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessages =\n goog.abstractMethod;\n\n\n/**\n * A low water-mark message count to notify the application when the\n * flow-control condition is cleared, that is, when the application is\n * able to send more messages.\n *\n * We expect the application to configure a high water-mark message count,\n * which is checked via getNonAckedMessageCount(). When the high water-mark\n * is exceeded, the application should install a callback via this method\n * to be notified when to start to send new messages.\n *\n * This is not yet implemented.\n *\n * @param {number} count The low water-mark count. It is an error to pass\n * a non-positive value.\n * @param {function()} callback The call back to notify the application\n * when NonAckedMessageCount is below the specified low water-mark count.\n * Any previously registered callback is cleared. This new callback will\n * be cleared once it has been fired, or when the channel is closed or aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method registers a callback to handle the commit request sent\n * by the server. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {function(!Object)} callback The callback will take an opaque\n * commitId which needs be passed back to the server when an ack-commit\n * response is generated by the client application, via ackCommit().\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method is used by the application to generate an ack-commit response\n * for the given commitId. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {!Object} commitId The commitId which denotes the commit request\n * from the server that needs be ack'ed.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\n\n\n/**\n * Transport-metadata support.\n *\n * TODO: getLastResponseHeaders (only for non-200 status)\n * TODO: getInitStatusCode (handshake)\n * TODO: getInitResponseHeaders (handshake)\n *\n * Note that response headers from client-initiated close (abort) are not\n * available.\n *\n * In future when client-initiated half-close is supported, its response status\n * will be available via this API.\n *\n * @return {number} The non-200 HTTP status code received that causes the\n * channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\n goog.abstractMethod;\n\n\n/**\n * Enum to indicate the current recovery state.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.State = {\n /** Initial state. */\n INIT: 'init',\n\n /** Once a failure has been detected. */\n FAILED: 'failed',\n\n /**\n * Once a recovery operation has been issued, e.g. a new request to resume\n * communication.\n */\n RECOVERING: 'recovering',\n\n /** The channel has been closed. */\n CLOSED: 'closed'\n};\n\n\n/**\n * Enum to indicate different failure conditions as detected by the webchannel\n * runtime.\n *\n * This enum is to be used only between the runtime and FailureRecovery module,\n * and new states are expected to be introduced in future.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\n /**\n * The HTTP response returned a non-successful http status code.\n */\n HTTP_ERROR: 'http_error',\n\n /**\n * The request was aborted.\n */\n ABORT: 'abort',\n\n /**\n * The request timed out.\n */\n TIMEOUT: 'timeout',\n\n /**\n * Exception was thrown while processing the request/response.\n */\n EXCEPTION: 'exception'\n};\n\n\n/**\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\n * mainly for debugging use.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\n\n\n/**\n * This method is for WebChannel runtime to set the current failure condition\n * and to provide a callback for the algorithm to signal to the runtime\n * when it is time to issue a recovery operation, e.g. a new request to the\n * server.\n *\n * Supported transitions include:\n * INIT->FAILED\n * FAILED->FAILED (re-entry ok)\n * RECOVERY->FAILED.\n *\n * Ignored if state == CLOSED.\n *\n * Advanced implementations are expected to track all the state transitions\n * and their timestamps for monitoring purposes.\n *\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\n * new failure condition generated by the WebChannel runtime.\n * @param {!Function} operation The callback function to the WebChannel\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\n * recovery algorithm will issue timeout-based recovery operations.\n * Post-condition for the callback: state transition to RECOVERING.\n *\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\n * as decided by the failure recovery module. Upon a recoverable failure event,\n * the state is transitioned to RECOVERING; or the state is transitioned to\n * FAILED which indicates a fail-fast decision for the runtime to execute.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\n\n\n/**\n * The Webchannel runtime needs call this method when webchannel is closed or\n * aborted.\n *\n * Once the instance is closed, any access to the instance will be a no-op.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\n\n\n/**\n * A request header to indicate to the server the messaging protocol\n * each HTTP message is speaking.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\n\n\n/**\n * The value for x-client-protocol when the messaging protocol is WebChannel.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\n\n\n/**\n * A response header for the server to signal the wire-protocol that\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\n * \"quic\". This information avoids the need to use private APIs to decide if\n * HTTP requests are multiplexed etc.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\n\n\n/**\n * A response header for the server to send back the HTTP session id as part of\n * the initial handshake. The value of the HTTP session id is opaque to the\n * WebChannel protocol.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\n\n\n/**\n * A response header for the server to send back any initial response data as a\n * header to avoid any possible buffering by an intermediary, which may\n * be undesired during the handshake.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\n\n\n/**\n * A request header for specifying the content-type of WebChannel messages,\n * e.g. application-defined JSON encoding styles. Currently this header\n * is sent by the client via initMessageHeaders when the channel is opened.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\n\n\n/**\n * A request header for specifying the client profile in order to apply\n * customized config params on the server side, e.g. timeouts.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Low level handling of XMLHttpRequest.\n */\n\ngoog.provide('goog.net.DefaultXmlHttpFactory');\ngoog.provide('goog.net.XmlHttp');\ngoog.provide('goog.net.XmlHttp.OptionType');\ngoog.provide('goog.net.XmlHttp.ReadyState');\ngoog.provide('goog.net.XmlHttpDefines');\n\ngoog.require('goog.asserts');\ngoog.require('goog.net.WrapperXmlHttpFactory');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.requireType('goog.net.XhrLike');\n\n\n/**\n * Static class for creating XMLHttpRequest objects.\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\n */\ngoog.net.XmlHttp = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.createInstance();\n};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true bypasses the ActiveX probing code.\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\n * out the ActiveX probing code from binaries. To achieve this, use\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\n * TODO(ruilopes): Collapse both defines.\n */\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\n\n\n/** @const */\ngoog.net.XmlHttpDefines = {};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true eliminates the ActiveX probing code.\n */\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\n\n\n/**\n * Gets the options to use with the XMLHttpRequest objects obtained using\n * the static methods.\n * @return {Object} The options.\n */\ngoog.net.XmlHttp.getOptions = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.getOptions();\n};\n\n\n/**\n * Type of options that an XmlHttp object can have.\n * @enum {number}\n */\ngoog.net.XmlHttp.OptionType = {\n /**\n * Whether a goog.nullFunction should be used to clear the onreadystatechange\n * handler instead of null.\n */\n USE_NULL_FUNCTION: 0,\n\n /**\n * NOTE(user): In IE if send() errors on a *local* request the readystate\n * is still changed to COMPLETE. We need to ignore it and allow the\n * try/catch around send() to pick up the error.\n */\n LOCAL_REQUEST_ERROR: 1,\n};\n\n\n/**\n * Status constants for XMLHTTP, matches:\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\n * @enum {number}\n */\ngoog.net.XmlHttp.ReadyState = {\n /**\n * Constant for when xmlhttprequest.readyState is uninitialized\n */\n UNINITIALIZED: 0,\n\n /**\n * Constant for when xmlhttprequest.readyState is loading.\n */\n LOADING: 1,\n\n /**\n * Constant for when xmlhttprequest.readyState is loaded.\n */\n LOADED: 2,\n\n /**\n * Constant for when xmlhttprequest.readyState is in an interactive state.\n */\n INTERACTIVE: 3,\n\n /**\n * Constant for when xmlhttprequest.readyState is completed\n */\n COMPLETE: 4,\n};\n\n\n/**\n * The global factory instance for creating XMLHttpRequest objects.\n * @type {goog.net.XmlHttpFactory}\n * @private\n */\ngoog.net.XmlHttp.factory_;\n\n\n/**\n * Sets the factories for creating XMLHttpRequest objects and their options.\n * @param {Function} factory The factory for XMLHttpRequest objects.\n * @param {Function} optionsFactory The factory for options.\n * @deprecated Use setGlobalFactory instead.\n */\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\n 'use strict';\n goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory(\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\n};\n\n\n/**\n * Sets the global factory object.\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\n */\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\n 'use strict';\n goog.net.XmlHttp.factory_ = factory;\n};\n\n\n\n/**\n * Default factory to use when creating xhr objects. You probably shouldn't be\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\n * @extends {goog.net.XmlHttpFactory}\n * @constructor\n */\ngoog.net.DefaultXmlHttpFactory = function() {\n 'use strict';\n goog.net.XmlHttpFactory.call(this);\n};\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const progId = this.getProgId_();\n if (progId) {\n return new ActiveXObject(progId);\n } else {\n return new XMLHttpRequest();\n }\n};\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\n 'use strict';\n const progId = this.getProgId_();\n const options = {};\n if (progId) {\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\n }\n return options;\n};\n\n\n/**\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\n * @type {string|undefined}\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\n\n\n/**\n * Initialize the private state used by other functions.\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\n 'use strict';\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\n return '';\n }\n\n // The following blog post describes what PROG IDs to use to create the\n // XMLHTTP object in Internet Explorer:\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\n // However we do not (yet) fully trust that this will be OK for old versions\n // of IE on Win9x so we therefore keep the last 2.\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\n typeof ActiveXObject != 'undefined') {\n // Candidate Active X types.\n const ACTIVE_X_IDENTS = [\n 'MSXML2.XMLHTTP.6.0',\n 'MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP',\n ];\n for (let i = 0; i < ACTIVE_X_IDENTS.length; i++) {\n const candidate = ACTIVE_X_IDENTS[i];\n\n try {\n new ActiveXObject(candidate);\n // NOTE(user): cannot assign progid and return candidate in one line\n // because JSCompiler complaings: BUG 658126\n this.ieProgId_ = candidate;\n return candidate;\n } catch (e) {\n // do nothing; try next choice\n }\n }\n\n // couldn't find any matches\n throw new Error(\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\n ' or MSXML might not be installed');\n }\n\n return /** @type {string} */ (this.ieProgId_);\n};\n\n\n// Set the global factory to an instance of the default factory.\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the ChannelRequest class. The request\n * object encapsulates the logic for making a single request, either for the\n * forward channel, back channel, or test channel, to the server. It contains\n * the logic for the two types of transports we use:\n * XMLHTTP and Image request. It provides timeout detection. More transports\n * to be added in future, such as Fetch, WebSocket.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\n\ngoog.require('goog.Timer');\ngoog.require('goog.asserts');\ngoog.require('goog.async.Throttle');\ngoog.require('goog.dispose');\ngoog.require('goog.events.EventHandler');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.labs.net.webChannel.Wire.QueuedMap');\ngoog.requireType('goog.net.XhrIo');\n\n\n\n/**\n * A new ChannelRequest is created for each request to the server.\n *\n * @param {goog.labs.net.webChannel.Channel} channel\n * The channel that owns this request.\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\n * WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.ChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n /**\n * The channel object that owns the request.\n * @private {goog.labs.net.webChannel.Channel}\n */\n this.channel_ = channel;\n\n /**\n * The channel debug to use for logging\n * @private {goog.labs.net.webChannel.WebChannelDebug}\n */\n this.channelDebug_ = channelDebug;\n\n /**\n * The Session ID for the channel.\n * @private {string|undefined}\n */\n this.sid_ = opt_sessionId;\n\n /**\n * The RID (request ID) for the request.\n * @private {string|number|undefined}\n */\n this.rid_ = opt_requestId;\n\n /**\n * The attempt number of the current request.\n * @private {number}\n */\n this.retryId_ = opt_retryId || 1;\n\n /**\n * An object to keep track of the channel request event listeners.\n * @private {!goog.events.EventHandler<\n * !goog.labs.net.webChannel.ChannelRequest>}\n */\n this.eventHandler_ = new goog.events.EventHandler(this);\n\n /**\n * The timeout in ms before failing the request.\n * @private {number}\n */\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\n\n /**\n * A timer for polling responseText in browsers that don't fire\n * onreadystatechange during incremental loading of responseText.\n * @private {goog.Timer}\n */\n this.pollingTimer_ =\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n\n /**\n * Whether the request was successful. This is only set to true after the\n * request successfully completes.\n * @private {boolean}\n */\n this.successful_ = false;\n\n\n /**\n * The TimerID of the timer used to detect if the request has timed-out.\n * @type {?number}\n * @private\n */\n this.watchDogTimerId_ = null;\n\n /**\n * The time in the future when the request will timeout.\n * @private {?number}\n */\n this.watchDogTimeoutTime_ = null;\n\n /**\n * The time the request started.\n * @private {?number}\n */\n this.requestStartTime_ = null;\n\n /**\n * The type of request (XMLHTTP, IMG)\n * @private {?number}\n */\n this.type_ = null;\n\n /**\n * The base Uri for the request. The includes all the parameters except the\n * one that indicates the retry number.\n * @private {?goog.Uri}\n */\n this.baseUri_ = null;\n\n /**\n * The request Uri that was actually used for the most recent request attempt.\n * @private {?goog.Uri}\n */\n this.requestUri_ = null;\n\n /**\n * The post data, if the request is a post.\n * @private {?string}\n */\n this.postData_ = null;\n\n /**\n * An array of pending messages that we have either received a non-successful\n * response for, or no response at all, and which therefore may or may not\n * have been received by the server.\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n\n /**\n * The XhrLte request if the request is using XMLHTTP\n * @private {?goog.net.XhrIo}\n */\n this.xmlHttp_ = null;\n\n /**\n * The position of where the next unprocessed chunk starts in the response\n * text.\n * @private {number}\n */\n this.xmlHttpChunkStart_ = 0;\n\n /**\n * The verb (Get or Post) for the request.\n * @private {?string}\n */\n this.verb_ = null;\n\n /**\n * The last error if the request failed.\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\n */\n this.lastError_ = null;\n\n /**\n * The last status code received.\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Whether the request has been cancelled due to a call to cancel.\n * @private {boolean}\n */\n this.cancelled_ = false;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n * If set to zero no throttle is used.\n *\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\n *\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * The throttle for readystatechange events for the current request, or null\n * if there is none.\n * @private {?goog.async.Throttle}\n */\n this.readyStateChangeThrottle_ = null;\n\n /**\n * Whether to the result is expected to be encoded for chunking and thus\n * requires decoding.\n * @private {boolean}\n */\n this.decodeChunks_ = false;\n\n /**\n * Whether to decode x-http-initial-response.\n * @private {boolean}\n */\n this.decodeInitialResponse_ = false;\n\n /**\n * Whether x-http-initial-response has been decoded (dispatched).\n * @private {boolean}\n */\n this.initialResponseDecoded_ = false;\n\n /**\n * Whether the first byte of response body has arrived, for a successful\n * response.\n * @private {boolean}\n */\n this.firstByteReceived_ = false;\n\n /**\n * The current state of fetch responses if webchannel is using WHATWG\n * fetch/streams.\n * @private {!goog.labs.net.webChannel.FetchResponseState}\n */\n this.fetchResponseState_ = new goog.labs.net.webChannel.FetchResponseState();\n};\n\n/**\n * A collection of fetch/stream properties.\n * @struct\n * @constructor\n */\ngoog.labs.net.webChannel.FetchResponseState = function() {\n 'use strict';\n /**\n * The TextDecoder for decoding Uint8Array responses from fetch request.\n * @type {?goog.global.TextDecoder}\n */\n this.textDecoder = null;\n\n /**\n * The unconsumed response text from the fetch requests.\n * @type {string}\n */\n this.responseBuffer = '';\n\n /**\n * Whether or not the response body has arrived.\n * @type {boolean}\n */\n this.responseArrivedForFetch = false;\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst Channel = goog.labs.net.webChannel.Channel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst FetchResponseState = goog.labs.net.webChannel.FetchResponseState;\nconst requestStats = goog.labs.net.webChannel.requestStats;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst environment = goog.labs.net.webChannel.environment;\n\n/**\n * Default timeout in MS for a request. The server must return data within this\n * time limit for the request to not timeout.\n * @private {number}\n */\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\n\n\n/**\n * Enum for channel requests type\n * @enum {number}\n * @private\n */\nChannelRequest.Type_ = {\n /**\n * XMLHTTP requests.\n */\n XML_HTTP: 1,\n\n /**\n * IMG requests.\n */\n CLOSE_REQUEST: 2\n};\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nChannelRequest.Error = {\n /**\n * Errors due to a non-200 status code.\n */\n STATUS: 0,\n\n /**\n * Errors due to no data being returned.\n */\n NO_DATA: 1,\n\n /**\n * Errors due to a timeout.\n */\n TIMEOUT: 2,\n\n /**\n * Errors due to the server returning an unknown.\n */\n UNKNOWN_SESSION_ID: 3,\n\n /**\n * Errors due to bad data being received.\n */\n BAD_DATA: 4,\n\n /**\n * Errors due to the handler throwing an exception.\n */\n HANDLER_EXCEPTION: 5,\n\n /**\n * The browser declared itself offline during the request.\n */\n BROWSER_OFFLINE: 6\n};\n\n\n/**\n * Returns a useful error string for debugging based on the specified error\n * code.\n * @param {?ChannelRequest.Error} errorCode The error code.\n * @param {number} statusCode The HTTP status code.\n * @return {string} The error string for the given code combination.\n */\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\n 'use strict';\n switch (errorCode) {\n case ChannelRequest.Error.STATUS:\n return 'Non-200 return code (' + statusCode + ')';\n case ChannelRequest.Error.NO_DATA:\n return 'XMLHTTP failure (no data)';\n case ChannelRequest.Error.TIMEOUT:\n return 'HttpConnection timeout';\n default:\n return 'Unknown error';\n }\n};\n\n\n/**\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\n * @private {!Object}\n */\nChannelRequest.INVALID_CHUNK_ = {};\n\n\n/**\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\n * response.\n * @private {!Object}\n */\nChannelRequest.INCOMPLETE_CHUNK_ = {};\n\n\n/**\n * Returns whether XHR streaming is supported on this browser.\n *\n * @return {boolean} Whether XHR streaming is supported.\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\n */\nChannelRequest.supportsXhrStreaming = function() {\n 'use strict';\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers.\n */\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Overrides the default HTTP method.\n *\n * @param {string} verb The HTTP method\n */\nChannelRequest.prototype.setVerb = function(verb) {\n 'use strict';\n this.verb_ = verb;\n};\n\n\n/**\n * Sets the timeout for a request\n *\n * @param {number} timeout The timeout in MS for when we fail the request.\n */\nChannelRequest.prototype.setTimeout = function(timeout) {\n 'use strict';\n this.timeout_ = timeout;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets the pending messages that this request is handling.\n *\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\n * The pending messages for this request.\n */\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\n 'use strict';\n this.pendingMessages_ = pendingMessages;\n};\n\n\n/**\n * Gets the pending messages that this request is handling, in case of a retry.\n *\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\n * messages for this request.\n */\nChannelRequest.prototype.getPendingMessages = function() {\n 'use strict';\n return this.pendingMessages_;\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP POST to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {?string} postData The data for the post body.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n */\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = postData;\n this.decodeChunks_ = decodeChunks;\n this.sendXmlHttp_(null /* hostPrefix */);\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP GET to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n * @param {?string} hostPrefix The host prefix, if we might be using a\n * secondary domain. Note that it should also be in the URL, adding this\n * won't cause it to be added to the URL.\n */\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = null;\n this.decodeChunks_ = decodeChunks;\n\n this.sendXmlHttp_(hostPrefix);\n};\n\n\n/**\n * Sends a request via XMLHTTP according to the current state of the request\n * object.\n *\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\n * domain.\n * @private\n */\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\n 'use strict';\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n\n // clone the base URI to create the request URI. The request uri has the\n // attempt number as a parameter which helps in debugging.\n this.requestUri_ = this.baseUri_.clone();\n this.requestUri_.setParameterValues('t', this.retryId_);\n\n // send the request either as a POST or GET\n this.xmlHttpChunkStart_ = 0;\n const useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\n this.fetchResponseState_ = new FetchResponseState();\n // If the request is a GET request, start a backchannel to transfer streaming\n // data. Note that WebChannel GET request can also be used for closing the\n // channel as in method ChannelRequest#sendCloseRequest.\n // The second parameter of Channel#createXhrIo is JS only.\n this.xmlHttp_ = this.channel_.createXhrIo(\n useSecondaryDomains ? hostPrefix : null, !this.postData_);\n\n if (this.readyStateChangeThrottleMs_ > 0) {\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\n this.readyStateChangeThrottleMs_);\n }\n\n this.eventHandler_.listen(\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\n this.readyStateChangeHandler_);\n\n const headers =\n this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\n if (this.postData_) {\n if (!this.verb_) {\n this.verb_ = 'POST';\n }\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\n } else {\n this.verb_ = 'GET';\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\n }\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_MADE);\n this.channelDebug_.xmlHttpChannelRequest(\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\n};\n\n\n/**\n * Handles a readystatechange event.\n * @param {goog.events.Event} evt The event.\n * @private\n */\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\n 'use strict';\n const xhr = /** @type {goog.net.XhrIo} */ (evt.target);\n const throttle = this.readyStateChangeThrottle_;\n if (throttle &&\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n // Only throttle in the partial data case.\n this.channelDebug_.debug('Throttling readystatechange.');\n throttle.fire();\n } else {\n // If we haven't throttled, just handle response directly.\n this.xmlHttpHandler_(xhr);\n }\n};\n\n\n/**\n * XmlHttp handler\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\n * @private\n */\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\n 'use strict';\n requestStats.onStartExecution();\n\n try {\n if (xmlhttp == this.xmlHttp_) {\n this.onXmlHttpReadyStateChanged_();\n } else {\n this.channelDebug_.warning(\n 'Called back with an ' +\n 'unexpected xmlhttp');\n }\n } catch (ex) {\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\n if (this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.dumpException(ex, function() {\n 'use strict';\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\n });\n } else {\n this.channelDebug_.dumpException(ex, 'No response text');\n }\n } finally {\n requestStats.onEndExecution();\n }\n};\n\n\n/**\n * Called by the readystate handler for XMLHTTP requests.\n *\n * @private\n */\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\n 'use strict';\n const readyState = this.xmlHttp_.getReadyState();\n const errorCode = this.xmlHttp_.getLastErrorCode();\n const statusCode = this.xmlHttp_.getStatus();\n\n // we get partial results in browsers that support ready state interactive.\n // We also make sure that getResponseText is not null in interactive mode\n // before we continue.\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\n !environment.isPollingRequired() && // otherwise, go on to startPolling\n !this.hasResponseBody_())) {\n return; // not yet ready\n }\n\n // Dispatch any appropriate network events.\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n errorCode != goog.net.ErrorCode.ABORT) {\n // Pretty conservative, these are the only known scenarios which we'd\n // consider indicative of a truly non-functional network connection.\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n } else {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\n }\n }\n\n // got some data so cancel the watchdog timer\n this.cancelWatchDogTimer_();\n\n const status = this.xmlHttp_.getStatus();\n this.lastStatusCode_ = status;\n const responseText = this.decodeXmlHttpResponse_();\n\n if (!this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'No response text for uri ' + channelRequest.requestUri_ +\n ' status ' + status;\n });\n }\n this.successful_ = (status == 200);\n\n this.channelDebug_.xmlHttpChannelResponseMetaData(\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\n this.retryId_, readyState, status);\n\n if (!this.successful_) {\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\n // the server error string will include 'Unknown SID' which indicates the\n // server doesn't know about the session (maybe it got restarted, maybe\n // the user got moved to another server, etc.,). Handlers can special\n // case this error\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\n } else {\n this.lastError_ = ChannelRequest.Error.STATUS;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\n this.channelDebug_.warning(\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\n }\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n\n if (this.shouldCheckInitialResponse_()) {\n const initialResponse = this.getInitialResponse_();\n if (initialResponse) {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, initialResponse,\n 'Initial handshake response via ' +\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n this.initialResponseDecoded_ = true;\n this.safeOnRequestData_(initialResponse);\n } else {\n this.successful_ = false;\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning(\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\n ' (' + this.rid_ + ')');\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n }\n\n if (this.decodeChunks_) {\n this.decodeNextChunks_(readyState, responseText);\n if (environment.isPollingRequired() && this.successful_ &&\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n this.startPolling_();\n }\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, null);\n this.safeOnRequestData_(responseText);\n }\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.cleanup_();\n }\n\n if (!this.successful_) {\n return;\n }\n\n if (!this.cancelled_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.channel_.onRequestComplete(this);\n } else {\n // The default is false, the result from this callback shouldn't carry\n // over to the next callback, otherwise the request looks successful if\n // the watchdog timer gets called\n this.successful_ = false;\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Whether we need check the initial-response header that is sent during the\n * fast handshake.\n *\n * @return {boolean} true if the initial-response header is yet to be processed.\n * @private\n */\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\n 'use strict';\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\n};\n\n\n/**\n * Queries the initial response header that is sent during the handshake.\n *\n * @return {?string} The non-empty header value or null.\n * @private\n */\nChannelRequest.prototype.getInitialResponse_ = function() {\n 'use strict';\n if (this.xmlHttp_) {\n const value = this.xmlHttp_.getStreamingResponseHeader(\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\n return value;\n }\n }\n\n return null;\n};\n\n\n/**\n * Check if the initial response header has been handled.\n *\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\n */\nChannelRequest.prototype.isInitialResponseDecoded = function() {\n 'use strict';\n return this.initialResponseDecoded_;\n};\n\n\n/**\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\n */\nChannelRequest.prototype.setDecodeInitialResponse = function() {\n 'use strict';\n this.decodeInitialResponse_ = true;\n};\n\n\n\n/**\n * Decodes the responses from XhrIo object.\n * @returns {string} responseText\n * @private\n */\nChannelRequest.prototype.decodeXmlHttpResponse_ = function() {\n 'use strict';\n if (!this.useFetchStreamsForResponse_()) {\n return this.xmlHttp_.getResponseText();\n }\n const responseChunks =\n /** @type {!Array<!Uint8Array>} */ (this.xmlHttp_.getResponse());\n let responseText = '';\n const responseLength = responseChunks.length;\n const requestCompleted =\n this.xmlHttp_.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n if (!this.fetchResponseState_.textDecoder) {\n if (typeof TextDecoder === 'undefined') {\n this.channelDebug_.severe(\n 'TextDecoder is not supported by this browser.');\n this.cleanup_();\n this.dispatchFailure_();\n return '';\n }\n this.fetchResponseState_.textDecoder = new goog.global.TextDecoder();\n }\n for (let i = 0; i < responseLength; i++) {\n this.fetchResponseState_.responseArrivedForFetch = true;\n const isLastChunk = requestCompleted && i == responseLength - 1;\n responseText += this.fetchResponseState_.textDecoder.decode(\n responseChunks[i], {stream: isLastChunk});\n }\n responseChunks.splice(0, responseLength);\n this.fetchResponseState_.responseBuffer += responseText;\n this.xmlHttpChunkStart_ = 0;\n return this.fetchResponseState_.responseBuffer;\n};\n\n\n/**\n * Whether or not the response has response body.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.hasResponseBody_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n if (this.fetchResponseState_.responseArrivedForFetch) {\n return true;\n }\n return !(!this.xmlHttp_.getResponseText() && !this.xmlHttp_.getResponse());\n};\n\n/**\n * Whether or not the response body is streamed.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.useFetchStreamsForResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n return (\n this.verb_ == 'GET' && this.type_ != ChannelRequest.Type_.CLOSE_REQUEST &&\n this.channel_.usesFetchStreams());\n};\n\n\n/**\n * Resets the response buffer if the saved chunk has been processed.\n * @private\n * @param {string|!Object|undefined} chunkText\n */\nChannelRequest.prototype.maybeResetBuffer_ = function(chunkText) {\n 'use strict';\n if (this.useFetchStreamsForResponse_() &&\n chunkText != ChannelRequest.INCOMPLETE_CHUNK_ &&\n chunkText != ChannelRequest.INVALID_CHUNK_) {\n this.fetchResponseState_.responseBuffer = '';\n this.xmlHttpChunkStart_ = 0;\n }\n};\n\n\n/**\n * Decodes the next set of available chunks in the response.\n * @param {number} readyState The value of readyState.\n * @param {string} responseText The value of responseText.\n * @private\n */\nChannelRequest.prototype.decodeNextChunks_ = function(\n readyState, responseText) {\n 'use strict';\n let decodeNextChunksSuccessful = true;\n\n let chunkText;\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\n chunkText = this.getNextChunk_(responseText);\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n // should have consumed entire response when the request is done\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\n decodeNextChunksSuccessful = false;\n }\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, null, '[Incomplete Response]');\n break;\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunk]');\n decodeNextChunksSuccessful = false;\n break;\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, /** @type {string} */ (chunkText), null);\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\n }\n }\n\n this.maybeResetBuffer_(chunkText);\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n responseText.length == 0 &&\n !this.fetchResponseState_.responseArrivedForFetch) {\n // also an error if we didn't get any response\n this.lastError_ = ChannelRequest.Error.NO_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\n decodeNextChunksSuccessful = false;\n }\n\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\n\n if (!decodeNextChunksSuccessful) {\n // malformed response - we make this trigger retry logic\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunked Response]');\n this.cleanup_();\n this.dispatchFailure_();\n } else {\n if (responseText.length > 0 && !this.firstByteReceived_) {\n this.firstByteReceived_ = true;\n this.channel_.onFirstByteReceived(this, responseText);\n }\n }\n};\n\n\n/**\n * Polls the response for new data.\n * @private\n */\nChannelRequest.prototype.pollResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return; // already closed\n }\n const readyState = this.xmlHttp_.getReadyState();\n const responseText = this.xmlHttp_.getResponseText();\n if (this.xmlHttpChunkStart_ < responseText.length) {\n this.cancelWatchDogTimer_();\n this.decodeNextChunks_(readyState, responseText);\n if (this.successful_ &&\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Starts a polling interval for changes to responseText of the\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\n * as data comes in incrementally. This timer is disabled in\n * cleanup_().\n * @private\n */\nChannelRequest.prototype.startPolling_ = function() {\n 'use strict';\n this.eventHandler_.listen(\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\n this.pollingTimer_.start();\n};\n\n\n/**\n * Returns the next chunk of a chunk-encoded response. This is not standard\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\n * the application through XMLHTTP. So we have an additional chunk encoding at\n * the application level that lets us tell where the beginning and end of\n * individual responses are so that we can only try to eval a complete JS array.\n *\n * The encoding is the size of the chunk encoded as a decimal string followed\n * by a newline followed by the data.\n *\n * @param {string} responseText The response text from the XMLHTTP response.\n * @return {string|!Object} The next chunk string or a sentinel object\n * indicating a special condition.\n * @private\n */\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\n 'use strict';\n const sizeStartIndex = this.xmlHttpChunkStart_;\n const sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\n if (sizeEndIndex == -1) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\n const size = Number(sizeAsString);\n if (isNaN(size)) {\n return ChannelRequest.INVALID_CHUNK_;\n }\n\n const chunkStartIndex = sizeEndIndex + 1;\n if (chunkStartIndex + size > responseText.length) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const chunkText = responseText.substr(chunkStartIndex, size);\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\n return chunkText;\n};\n\n\n/**\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\n *\n * This is only currently used to terminate the connection, as an IMG tag is\n * the most reliable way to send something to the server while the page\n * is getting torn down.\n *\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\n * solution to ensure delivery without blocking window close. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\n *\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\n * Policy (CSP) violation of using an IMG tag.\n *\n * For react-native, we use xhr to send the actual close request, and assume\n * there is no page-close issue with react-native.\n *\n * @param {goog.Uri} uri The uri to send a request to.\n */\nChannelRequest.prototype.sendCloseRequest = function(uri) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\n this.baseUri_ = uri.clone().makeUnique();\n\n let requestSent = false;\n\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\n // empty string body to avoid 413 error on chrome < 41\n requestSent =\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\n }\n\n if (!requestSent && goog.global.Image) {\n const eltImg = new Image();\n eltImg.src = this.baseUri_;\n requestSent = true;\n }\n\n if (!requestSent) {\n // no handler is set to match the sendBeacon/Image behavior\n this.xmlHttp_ = this.channel_.createXhrIo(null);\n this.xmlHttp_.send(this.baseUri_);\n }\n\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n};\n\n\n/**\n * Cancels the request no matter what the underlying transport is.\n */\nChannelRequest.prototype.cancel = function() {\n 'use strict';\n this.cancelled_ = true;\n this.cleanup_();\n};\n\n\n/**\n * Resets the timeout.\n *\n * @param {number=} opt_timeout The new timeout\n */\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\n 'use strict';\n if (opt_timeout) {\n this.setTimeout(opt_timeout);\n }\n // restart only if a timer is currently set\n if (this.watchDogTimerId_) {\n this.cancelWatchDogTimer_();\n this.ensureWatchDogTimer_();\n }\n};\n\n\n/**\n * Ensures that there is watchdog timeout which is used to ensure that\n * the connection completes in time.\n *\n * @private\n */\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\n 'use strict';\n this.watchDogTimeoutTime_ = Date.now() + this.timeout_;\n this.startWatchDogTimer_(this.timeout_);\n};\n\n\n/**\n * Starts the watchdog timer which is used to ensure that the connection\n * completes in time.\n * @param {number} time The number of milliseconds to wait.\n * @private\n */\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\n 'use strict';\n if (this.watchDogTimerId_ != null) {\n // assertion\n throw new Error('WatchDog timer not null');\n }\n this.watchDogTimerId_ =\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\n};\n\n\n/**\n * Cancels the watchdog timer if it has been started.\n *\n * @private\n */\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\n 'use strict';\n if (this.watchDogTimerId_) {\n goog.global.clearTimeout(this.watchDogTimerId_);\n this.watchDogTimerId_ = null;\n }\n};\n\n\n/**\n * Called when the watchdog timer is triggered. It also handles a case where it\n * is called too early which we suspect may be happening sometimes\n * (not sure why)\n *\n * @private\n */\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\n 'use strict';\n this.watchDogTimerId_ = null;\n const now = Date.now();\n goog.asserts.assert(\n this.watchDogTimeoutTime_, 'WatchDog timeout time missing?');\n if (now - this.watchDogTimeoutTime_ >= 0) {\n this.handleTimeout_();\n } else {\n // got called too early for some reason\n this.channelDebug_.warning('WatchDog timer called too early');\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\n }\n};\n\n\n/**\n * Called when the request has actually timed out. Will cleanup and notify the\n * channel of the failure.\n *\n * @private\n */\nChannelRequest.prototype.handleTimeout_ = function() {\n 'use strict';\n if (this.successful_) {\n // Should never happen.\n this.channelDebug_.severe(\n 'Received watchdog timeout even though request loaded successfully');\n }\n\n this.channelDebug_.timeoutResponse(this.requestUri_);\n\n // IMG or SendBeacon requests never notice if they were successful,\n // and always 'time out'. This fact says nothing about reachability.\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\n }\n\n this.cleanup_();\n\n // Set error and dispatch failure.\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\n this.dispatchFailure_();\n};\n\n\n/**\n * Notifies the channel that this request failed.\n * @private\n */\nChannelRequest.prototype.dispatchFailure_ = function() {\n 'use strict';\n if (this.channel_.isClosed() || this.cancelled_) {\n return;\n }\n\n this.channel_.onRequestComplete(this);\n};\n\n\n/**\n * Cleans up the objects used to make the request. This function is\n * idempotent.\n *\n * @private\n */\nChannelRequest.prototype.cleanup_ = function() {\n 'use strict';\n this.cancelWatchDogTimer_();\n\n goog.dispose(this.readyStateChangeThrottle_);\n this.readyStateChangeThrottle_ = null;\n\n // Stop the polling timer, if necessary.\n this.pollingTimer_.stop();\n\n // Unhook all event handlers.\n this.eventHandler_.removeAll();\n\n if (this.xmlHttp_) {\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\n // inside abort\n const xmlhttp = this.xmlHttp_;\n this.xmlHttp_ = null;\n xmlhttp.abort();\n xmlhttp.dispose();\n }\n};\n\n\n/**\n * Indicates whether the request was successful. Only valid after the handler\n * is called to indicate completion of the request.\n *\n * @return {boolean} True if the request succeeded.\n */\nChannelRequest.prototype.getSuccess = function() {\n 'use strict';\n return this.successful_;\n};\n\n\n/**\n * If the request was not successful, returns the reason.\n *\n * @return {?ChannelRequest.Error} The last error.\n */\nChannelRequest.prototype.getLastError = function() {\n 'use strict';\n return this.lastError_;\n};\n\n\n/**\n * Returns the status code of the last request.\n * @return {number} The status code of the last request.\n */\nChannelRequest.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * Returns the session id for this channel.\n *\n * @return {string|undefined} The session ID.\n */\nChannelRequest.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Returns the request id for this request. Each request has a unique request\n * id and the request IDs are a sequential increasing count.\n *\n * @return {string|number|undefined} The request ID.\n */\nChannelRequest.prototype.getRequestId = function() {\n 'use strict';\n return this.rid_;\n};\n\n\n/**\n * Returns the data for a post, if this request is a post.\n *\n * @return {?string} The POST data provided by the request initiator.\n */\nChannelRequest.prototype.getPostData = function() {\n 'use strict';\n return this.postData_;\n};\n\n\n/**\n * Returns the XhrIo request object.\n *\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\n */\nChannelRequest.prototype.getXhr = function() {\n 'use strict';\n return this.xmlHttp_;\n};\n\n\n/**\n * Returns the time that the request started, if it has started.\n *\n * @return {?number} The time the request started, as returned by Date.now().\n */\nChannelRequest.prototype.getRequestStartTime = function() {\n 'use strict';\n return this.requestStartTime_;\n};\n\n\n/**\n * Helper to call the callback's onRequestData, which catches any\n * exception.\n * @param {string} data The request data.\n * @private\n */\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\n 'use strict';\n try {\n this.channel_.onRequestData(this, data);\n const stats = requestStats.ServerReachability;\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\n } catch (e) {\n // Dump debug info, but keep going without closing the channel.\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\n }\n};\n\n\n/**\n * Convenience factory method.\n *\n * @param {Channel} channel The channel object that owns this request.\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @return {!ChannelRequest} The created channel request.\n */\nChannelRequest.createChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n return new ChannelRequest(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A single module to define user-agent specific environment\n * details.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.environment');\n\ngoog.module.declareLegacyNamespace();\n\nvar userAgent = goog.require('goog.userAgent');\n\n\n/**\n * The default polling interval in millis for Edge.\n *\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\n * chunk arrives within 50ms following the previous chunk. This may be fixed\n * in future, which requires changes to the whatwg spec too.\n *\n * @private @const {number}\n */\nvar EDGE_POLLING_INTERVAL_ = 125;\n\n\n/**\n * History:\n *\n * IE11 is still using Trident, the traditional engine for IE.\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\n *\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\n * and then to Blink (chrome).\n *\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\n * that may still be affected. For old Opera, double the polling interval\n * to 250ms.\n *\n * @return {boolean} True if polling is required with XHR.\n */\nexports.isPollingRequired = function() {\n return userAgent.EDGE_OR_IE;\n};\n\n\n/**\n * How often to poll (in MS) for changes to responseText in browsers that don't\n * fire onreadystatechange during incremental loading of the response body.\n *\n * @return {number|undefined} The polling interval (MS) for the current U-A;\n * or undefined if polling is not supposed to be enabled.\n */\nexports.getPollingInterval = function() {\n if (userAgent.EDGE_OR_IE) {\n return EDGE_POLLING_INTERVAL_;\n }\n\n return undefined;\n};\n\n/**\n * Origin trial token for google.com\n *\n * https://developers.chrome.com/origintrials/#/trials\n *\n * http://googlechrome.github.io/OriginTrials/check-token.html\n * Origin: https://google.com:443\n * Matches Subdomains? Yes\n * Matches Third-party? Yes\n * Feature: FetchUploadStreaming\n * Up to Chrome 95 (ends with the rollout of next Chrome release), no later\n * than Nov 9, 2021\n *\n * Token for googleapis.com will be registered after google.com's is deployed.\n *\n */\nconst OT_TOKEN_GOOGLE_COM =\n 'A0eNbltY1nd4MP7XTHXnTxWogDL6mWTdgIIKfKOTJoUHNbFFMZQBoiHHjJ9UK9lgYndWFaxOWR7ld8uUjcWmcwIAAAB/eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IkZldGNoVXBsb2FkU3RyZWFtaW5nIiwiZXhwaXJ5IjoxNjM2NTAyMzk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ==';\n\n\n/**\n * Creates ReadableStream to upload\n * @return {!ReadableStream} ReadableStream to upload\n */\nfunction createStream() {\n const encoder = new goog.global.TextEncoder();\n return new goog.global.ReadableStream({\n start: controller => {\n for (const obj of ['test\\r\\n', 'test\\r\\n']) {\n controller.enqueue(encoder.encode(obj));\n }\n controller.close();\n }\n });\n}\n\n/**\n * Detect the user agent is chrome and its version is higher than M90.\n * This code is hard-coded from goog.labs.userAgent.browser to avoid file size\n * increasing.\n * @return {boolean} Whether the above is true.\n */\nfunction isChromeM90OrHigher() {\n const userAgentStr = function() {\n const navigator = goog.global.navigator;\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n }();\n\n const matchUserAgent = function(str) {\n return userAgentStr.indexOf(str) != -1;\n };\n\n if (!matchUserAgent('Chrome') || matchUserAgent('Edg')) {\n return false;\n }\n\n const match = /Chrome\\/(\\d+)/.exec(userAgentStr);\n const chromeVersion = parseInt(match[1], 10);\n return chromeVersion >= 90;\n}\n\n/**\n * Detect the URL origin is *.google.com.\n * @param {string} url The target URL.\n * @return {boolean} Whether the above is true.\n */\nfunction isUrlGoogle(url) {\n const match = /\\/\\/([^\\/]+)\\//.exec(url);\n if (!match) {\n return false;\n }\n const origin = match[1];\n return origin.endsWith('google.com');\n}\n\n/**\n * The flag to run the origin trials code only once.\n */\nlet isStartOriginTrialsCalled = false;\n\n/**\n * For Fetch/upload OT, make three requests against the server endpoint.\n * POST requests contain only dummy payload.\n *\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * This function is expected to be called from background during the handshake.\n * Exceptions will be logged by the caller.\n *\n * No stats or logs are collected on the client-side. To be disabled once the\n * OT is expired.\n *\n * @param {string} path The base URL path for the requests\n * @param {function(*)} logError A function to execute when exceptions are\n * caught.\n */\nexports.startOriginTrials = function(path, logError) {\n if (isStartOriginTrialsCalled) {\n return;\n }\n isStartOriginTrialsCalled = true;\n // NE: may need check if path has already contains query params?\n\n // Accept only Chrome M90 or later due to service worker support.\n if (!isChromeM90OrHigher()) {\n return;\n }\n\n // Accept only only google.com and subdoamins.\n if (!isUrlGoogle(path)) {\n return;\n }\n // Since 3P OT is not supported yet, we should check the current page matches\n // the path (absolute one?) to disable this OT for cross-origin calls\n if (!window || !window.document || !isUrlGoogle(window.document.URL)) {\n return;\n }\n\n // Enable origin trial by injecting OT <meta> tag\n const tokenElement =\n /** @type {! HTMLMetaElement} */ (document.createElement('meta'));\n tokenElement.httpEquiv = 'origin-trial';\n tokenElement.content = OT_TOKEN_GOOGLE_COM;\n // appendChild() synchronously enables OT.\n document.head.appendChild(tokenElement);\n\n // Check if fetch upload stream is actually enabled.\n // By the spec, Streaming request doesn't has the Content-Type header:\n // https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n // If Chrome doesn't support Streaming, the body stream is converted to a\n // string \"[object ReadableStream]\" for fallback then it has \"Content-Type:\n // text/plain;charset=UTF-8\".\n const supportsRequestStreams = !new Request('', {\n body: new ReadableStream(),\n method: 'POST',\n }).headers.has('Content-Type');\n if (!supportsRequestStreams) {\n return;\n }\n\n // 1st req: path?ot=1\n // non-streaming upload request\n goog.global.fetch(`${path}?ot=1`, {method: 'POST', body: 'test\\r\\n'})\n .catch(logError);\n\n // 2nd req: path?ot=2\n // h2-only streaming upload request\n goog.global\n .fetch(`${path}?ot=2`, {\n method: 'POST',\n body: createStream(),\n allowHTTP1ForStreamingUpload: false,\n })\n .catch(logError);\n\n // 3rd req: path?ot=3\n // h1-allowed streaming upload request\n goog.global\n .fetch(`${path}?ot=3`, {\n method: 'POST',\n body: createStream(),\n allowHTTP1ForStreamingUpload: true,\n })\n .catch(logError);\n\n // Example calling a Chrome API:\n // goog.global.chrome.loadTimes().wasFetchedViaSpdy\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base WebChannel implementation.\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\n\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.async.run');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.ConnectionState');\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.labs.net.webChannel.WireV8');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.netUtils');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XhrIo');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.require('goog.net.rpc.HttpCors');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.structs');\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst ConnectionState = goog.labs.net.webChannel.ConnectionState;\nconst ForwardChannelRequestPool =\n goog.labs.net.webChannel.ForwardChannelRequestPool;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst Wire = goog.labs.net.webChannel.Wire;\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst environment = goog.labs.net.webChannel.environment;\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\nconst httpCors = goog.module.get('goog.net.rpc.HttpCors');\n\n/**\n * @define {boolean} If WebChannel should compile with Origin Trial features.\n */\nconst ALLOW_ORIGIN_TRIAL_FEATURES =\n goog.define('goog.net.webChannel.ALLOW_ORIGIN_TRIAL_FEATURES', true);\n\n/**\n * Gets an internal channel parameter in a type-safe way.\n *\n * @param {string} paramName the key of the parameter to fetch.\n * @param {!T} defaultValue the default value to return\n * @param {!goog.net.WebChannel.Options=} options Configuration for the\n * WebChannel instance.\n * @return {T}\n * @template T\n */\nfunction getInternalChannelParam(paramName, defaultValue, options) {\n if (!options || !options.internalChannelParams) {\n return defaultValue;\n }\n return /** @type {T} */ (options.internalChannelParams[paramName]) ||\n defaultValue;\n}\n\n/**\n * This WebChannel implementation is branched off goog.net.BrowserChannel\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\n * ported to this implementation as needed.\n *\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * WebChannel instance.\n * @param {number=} opt_clientVersion An application-specific version number\n * that is sent to the server when connected.\n * @param {!ConnectionState=} opt_conn Previously determined connection\n * conditions.\n * @constructor\n * @struct\n * @implements {goog.labs.net.webChannel.Channel}\n */\ngoog.labs.net.webChannel.WebChannelBase = function(\n opt_options, opt_clientVersion, opt_conn) {\n 'use strict';\n /**\n * The client library version (capabilities).\n * @private {number}\n */\n this.clientVersion_ = opt_clientVersion || 0;\n\n /**\n * The server library version (capabilities).\n * @private {number}\n */\n this.serverVersion_ = 0;\n\n\n /**\n * An array of queued maps that need to be sent to the server.\n * @private {!Array<Wire.QueuedMap>}\n */\n this.outgoingMaps_ = [];\n\n /**\n * The channel debug used for logging\n * @private {!WebChannelDebug}\n */\n this.channelDebug_ = new WebChannelDebug();\n\n /**\n * Connectivity state.\n * @private {!ConnectionState}\n */\n this.connState_ = opt_conn || new ConnectionState();\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n /**\n * Extra HTTP headers to add to the init request(s) sent to the server.\n * @private {?Object}\n */\n this.initHeaders_ = null;\n\n /**\n * @private {?string} The URL param name to overwrite custom HTTP headers\n * to bypass CORS preflight.\n */\n this.httpHeadersOverwriteParam_ = null;\n\n /**\n * Extra parameters to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraParams_ = null;\n\n /**\n * Parameter name for the http session id.\n * @private {?string}\n */\n this.httpSessionIdParam_ = null;\n\n /**\n * The http session id, to be sent with httpSessionIdParam_ with each\n * request after the initial handshake.\n * @private {?string}\n */\n this.httpSessionId_ = null;\n\n /**\n * The ChannelRequest object for the backchannel.\n * @private {?ChannelRequest}\n */\n this.backChannelRequest_ = null;\n\n /**\n * The relative path (in the context of the page hosting the browser channel)\n * for making requests to the server.\n * @private {?string}\n */\n this.path_ = null;\n\n /**\n * The absolute URI for the forwardchannel request.\n * @private {?goog.Uri}\n */\n this.forwardChannelUri_ = null;\n\n /**\n * The absolute URI for the backchannel request.\n * @private {?goog.Uri}\n */\n this.backChannelUri_ = null;\n\n /**\n * A subdomain prefix for using a subdomain in IE for the backchannel\n * requests.\n * @private {?string}\n */\n this.hostPrefix_ = null;\n\n /**\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\n * @private {boolean}\n */\n this.allowHostPrefix_ = true;\n\n /**\n * The next id to use for the RID (request identifier) parameter. This\n * identifier uniquely identifies the forward channel request.\n * @private {number}\n */\n this.nextRid_ = 0;\n\n /**\n * The id to use for the next outgoing map. This identifier uniquely\n * identifies a sent map.\n * @private {number}\n */\n this.nextMapId_ = 0;\n\n /**\n * Whether to fail forward-channel requests after one try or a few tries.\n * @private {boolean}\n */\n this.failFast_ = getInternalChannelParam('failFast', false, opt_options);\n\n /**\n * The handler that receive callbacks for state changes and data.\n * @private {?goog.labs.net.webChannel.WebChannelBase.Handler}\n */\n this.handler_ = null;\n\n /**\n * Timer identifier for asynchronously making a forward channel request.\n * This is set to true if the func is scheduled with async.run, which\n * is equivalent to setTimeout(0).\n * @private {?number|?boolean}\n */\n this.forwardChannelTimerId_ = null;\n\n /**\n * Timer identifier for asynchronously making a back channel request.\n * @private {?number}\n */\n this.backChannelTimerId_ = null;\n\n /**\n * Timer identifier for the timer that waits for us to retry the backchannel\n * in the case where it is dead and no longer receiving data.\n * @private {?number}\n */\n this.deadBackChannelTimerId_ = null;\n\n /**\n * Whether the client's network conditions can support streamed responses.\n * @private {?boolean}\n */\n this.enableStreaming_ = null;\n\n /**\n * Whether streaming mode is allowed. In certain debugging situations, it's\n * useful to disable this.\n * @private {boolean}\n */\n this.allowStreamingMode_ = true;\n\n /**\n * The array identifier of the last array received from the server for the\n * backchannel request.\n * @private {number}\n */\n this.lastArrayId_ = -1;\n\n /**\n * The array id of the last array sent by the server that we know about.\n * @private {number}\n */\n this.lastPostResponseArrayId_ = -1;\n\n /**\n * The last status code received (until `State.CLOSED` is reached).\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Number of times we have retried the current forward channel request.\n * @private {number}\n */\n this.forwardChannelRetryCount_ = 0;\n\n /**\n * Number of times in a row that we have retried the current back channel\n * request and received no data.\n * @private {number}\n */\n this.backChannelRetryCount_ = 0;\n\n /**\n * The attempt id for the current back channel request. Starts at 1 and\n * increments for each reconnect. The server uses this to log if our\n * connection is flaky or not.\n * @private {number}\n */\n this.backChannelAttemptId_ = 0;\n\n /**\n * The base part of the time before firing next retry request. Default is 5\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\n * for all retries, and linear backoff is applied to the sum for subsequent\n * retries.\n * @private {number}\n */\n this.baseRetryDelayMs_ =\n getInternalChannelParam('baseRetryDelayMs', 5 * 1000, opt_options);\n\n /**\n * A random time between 0 and this number of MS is added to the\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\n * @private {number}\n */\n this.retryDelaySeedMs_ =\n getInternalChannelParam('retryDelaySeedMs', 10 * 1000, opt_options);\n\n /**\n * Maximum number of attempts to connect to the server for forward channel\n * requests. Defaults to 2.\n * @private {number}\n */\n this.forwardChannelMaxRetries_ =\n getInternalChannelParam('forwardChannelMaxRetries', 2, opt_options);\n\n /**\n * The timeout in milliseconds for a forward channel request. Defaults to 20\n * seconds. Note that part of this timeout can be randomized.\n * @private {number}\n */\n this.forwardChannelRequestTimeoutMs_ = getInternalChannelParam(\n 'forwardChannelRequestTimeoutMs', 20 * 1000, opt_options);\n\n /**\n * The custom factory used to create XMLHttpRequest objects.\n * @private {!goog.net.XmlHttpFactory | undefined}\n */\n this.xmlHttpFactory_ =\n (opt_options && opt_options.xmlHttpFactory) || undefined;\n\n /**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @private {boolean}\n */\n this.usesFetchStreams_ =\n (opt_options && opt_options.useFetchStreams) || false;\n\n /**\n * The timeout in milliseconds for a back channel request. Defaults to using\n * the timeout configured in ChannelRequest (45s). If server-side\n * keepaliveInterval is known to the client, set the backchannel request\n * timeout to 1.5 * keepaliveInterval (ms).\n *\n * @private {number|undefined}\n */\n this.backChannelRequestTimeoutMs_ = undefined;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n *\n * This throttle is useful if the server sends large data chunks down the\n * backchannel. It prevents examining XHR partial data on every readystate\n * change event. This is useful because large chunks can trigger hundreds\n * of readystatechange events, each of which takes ~5ms or so to handle,\n * in turn making the UI unresponsive for a significant period.\n *\n * If set to zero no throttle is used.\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * Whether cross origin requests are supported for the channel.\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @private {boolean}\n */\n this.supportsCrossDomainXhrs_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * The current session id.\n * @private {string}\n */\n this.sid_ = '';\n\n /**\n * The current ChannelRequest pool for the forward channel.\n * @private {!ForwardChannelRequestPool}\n */\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\n opt_options && opt_options.concurrentRequestLimit);\n\n /**\n * The V8 codec.\n * @private {!WireV8}\n */\n this.wireCodec_ = new WireV8();\n\n /**\n * Whether to turn on the fast handshake behavior.\n *\n * @private {boolean}\n */\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\n\n /**\n * Whether to encode initMessageHeaders in the body.\n *\n * @private {boolean}\n */\n this.encodeInitMessageHeaders_ =\n (opt_options && opt_options.encodeInitMessageHeaders) || false;\n\n if (this.fastHandshake_ && this.encodeInitMessageHeaders_) {\n this.channelDebug_.warning(\n 'Ignore encodeInitMessageHeaders because fastHandshake is set.');\n this.encodeInitMessageHeaders_ = false;\n }\n\n /**\n * Whether to signal to the server to enable blocking handshake.\n *\n * @private {boolean}\n */\n this.blockingHandshake_ =\n (opt_options && opt_options.blockingHandshake) || false;\n\n\n if (opt_options && opt_options.disableRedact) {\n this.channelDebug_.disableRedact();\n }\n\n if (opt_options && opt_options.forceLongPolling) {\n this.allowStreamingMode_ = false;\n }\n\n /**\n * Whether to detect buffering proxies.\n *\n * fastHandshake + detectBufferingProxy are yet to be implemented.\n *\n * @private {boolean}\n */\n this.detectBufferingProxy_ =\n (!this.fastHandshake_ && this.allowStreamingMode_ && opt_options &&\n opt_options.detectBufferingProxy) ||\n false;\n\n /**\n * Callback when all the pending client-sent messages have been flushed.\n *\n * @private {function()|undefined}\n */\n this.forwardChannelFlushedCallback_ = undefined;\n\n /**\n * TODO(user): move all backchannel states to its own class similar to\n * forwardchannelrequestpool.js and log more stats.\n *\n * The estimated handshake RTT (ms) as measured from when the handshake\n * request is sent and when the handshake response headers are received.\n * If the value is 0, the RTT is unknown.\n *\n * @private {number}\n */\n this.handshakeRttMs_ = 0;\n\n /**\n * If BP detection is done or still in progress.\n * Should only be checked when detectBufferingProxy is turned on.\n * @private {boolean}\n */\n this.bpDetectionDone_ = false;\n\n /**\n * The timer for detecting buffering proxy. This needs be reset with each\n * backchannel request. If this is not null, bpDetectionDone_ == false.\n * @private {?number}\n */\n this.bpDetectionTimerId_ = null;\n\n /***\n * Whether to attempt Chrome Origin Trials as part of the handshake.\n * @private @const {boolean}\n */\n this.enableOriginTrials_ = ALLOW_ORIGIN_TRIAL_FEATURES &&\n (!opt_options || opt_options.enableOriginTrials !== false);\n\n /**\n * The array of non-acked maps at the time of channel close. Refer to\n * `getNonAckedMessagesWithClosedChannel()` API for definitions of non-acked\n * messages.\n *\n * @private {?Array<!Wire.QueuedMap>}\n */\n this.nonAckedMapsAtChannelClose_ = null;\n};\n\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\n\n\n/**\n * The channel version that we negotiated with the server for this session.\n * Starts out as the version we request, and then is changed to the negotiated\n * version after the initial open.\n * @private {number}\n */\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\n\n\n/**\n * Enum type for the channel state machine.\n * @enum {number}\n */\nWebChannelBase.State = {\n /** The channel is closed. */\n CLOSED: 0,\n\n /** The channel has been initialized but hasn't yet initiated a connection. */\n INIT: 1,\n\n /** The channel is in the process of opening a connection to the server. */\n OPENING: 2,\n\n /** The channel is open. */\n OPENED: 3\n};\n\n\n/**\n * The current state of the WebChannel.\n * @private {!WebChannelBase.State}\n */\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\n\n\n/**\n * The timeout in milliseconds for a forward channel request.\n * @type {number}\n */\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\n\n\n/**\n * Maximum number of attempts to connect to the server for back channel\n * requests.\n * @type {number}\n */\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\n\n\n/**\n * A number in MS of how long we guess the maxmium amount of time a round trip\n * to the server should take. In the future this could be substituted with a\n * real measurement of the RTT.\n * @type {number}\n */\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\n\n\n/**\n * When retrying for an inactive channel, we will multiply the total delay by\n * this number.\n * @type {number}\n */\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nWebChannelBase.Error = {\n /** Value that indicates no error has occurred. */\n OK: 0,\n\n /** An error due to a request failing. */\n REQUEST_FAILED: 2,\n\n /** An error due to the user being logged out. */\n LOGGED_OUT: 4,\n\n /** An error due to server response which contains no data. */\n NO_DATA: 5,\n\n /** An error due to a server response indicating an unknown session id */\n UNKNOWN_SESSION_ID: 6,\n\n /** An error due to a server response requesting to stop the channel. */\n STOP: 7,\n\n /** A general network error. */\n NETWORK: 8,\n\n /** An error due to bad data being returned from the server. */\n BAD_DATA: 10,\n\n /** An error due to a response that is not parsable. */\n BAD_RESPONSE: 11\n};\n\n\n/**\n * Internal enum type for the two channel types.\n * @enum {number}\n * @private\n */\nWebChannelBase.ChannelType_ = {\n FORWARD_CHANNEL: 1,\n\n BACK_CHANNEL: 2\n};\n\n\n/**\n * The maximum number of maps that can be sent in one POST. Should match\n * MAX_MAPS_PER_REQUEST on the server code.\n * @type {number}\n * @private\n */\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\n\n\n/**\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\n * handshake.\n *\n * @const @private {number}\n */\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\n\n\n/**\n * A guess at a cutoff at which to no longer assume the backchannel is dead\n * when we are slow to receive data. Number in bytes.\n *\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\n * @type {number}\n */\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\n\n\n/**\n * @return {number} The server version or 0 if undefined\n */\nWebChannelBase.prototype.getServerVersion = function() {\n 'use strict';\n return this.serverVersion_;\n};\n\n\n/**\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\n */\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\n 'use strict';\n return this.forwardChannelRequestPool_;\n};\n\n\n/**\n * @return {!Object} The codec object.\n */\nWebChannelBase.prototype.getWireCodec = function() {\n 'use strict';\n return this.wireCodec_;\n};\n\n\n/**\n * Returns the logger.\n *\n * @return {!WebChannelDebug} The channel debug object.\n */\nWebChannelBase.prototype.getChannelDebug = function() {\n 'use strict';\n return this.channelDebug_;\n};\n\n\n/**\n * Sets the logger.\n *\n * @param {!WebChannelDebug} channelDebug The channel debug object.\n */\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\n 'use strict';\n this.channelDebug_ = channelDebug;\n};\n\n\n/**\n * Starts the channel. This initiates connections to the server.\n *\n * @param {string} channelPath The path for the channel connection.\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\n * the requests.\n * @param {string=} opt_oldSessionId Session ID from a previous session.\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\n */\nWebChannelBase.prototype.connect = function(\n channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\n 'use strict';\n this.channelDebug_.debug('connect()');\n\n this.startOriginTrials_(channelPath);\n\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\n\n this.path_ = channelPath;\n this.extraParams_ = opt_extraParams || {};\n\n // Attach parameters about the previous session if reconnecting.\n if (opt_oldSessionId && opt_oldArrayId !== undefined) {\n this.extraParams_['OSID'] = opt_oldSessionId;\n this.extraParams_['OAID'] = opt_oldArrayId;\n }\n\n this.enableStreaming_ = this.allowStreamingMode_;\n this.connectChannel_();\n};\n\n\n/**\n * Disconnects and closes the channel.\n */\nWebChannelBase.prototype.disconnect = function() {\n 'use strict';\n this.channelDebug_.debug('disconnect()');\n\n this.cancelRequests_();\n\n if (this.state_ == WebChannelBase.State.OPENED) {\n const rid = this.nextRid_++;\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('TYPE', 'terminate');\n\n this.addAdditionalParams_(uri);\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid);\n request.sendCloseRequest(uri);\n }\n\n this.onClose_();\n};\n\n\n/**\n * Returns the session id of the channel. Only available after the\n * channel has been opened.\n * @return {string} Session ID.\n */\nWebChannelBase.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Starts the connection.\n * @private\n */\nWebChannelBase.prototype.connectChannel_ = function() {\n 'use strict';\n this.channelDebug_.debug('connectChannel_()');\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\n this.forwardChannelUri_ =\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\n this.ensureForwardChannel_();\n};\n\n\n/**\n * Starts the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.startOriginTrials_ = function(channelPath) {\n 'use strict';\n\n if (!this.enableOriginTrials_) {\n return;\n }\n\n this.channelDebug_.info('Origin Trials enabled.');\n goog.async.run(goog.bind(this.runOriginTrials_, this, channelPath));\n};\n\n\n/**\n * Runs the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.runOriginTrials_ = function(channelPath) {\n 'use strict';\n\n try {\n // Since startOriginTrials might throw exceptions asynchronously, we should\n // capture it in promise-catch.\n environment.startOriginTrials(channelPath, e => {\n this.channelDebug_.dumpException(\n /** @type {?Error} */ (e), 'Error in running origin trials');\n });\n this.channelDebug_.info('Origin Trials invoked: ' + channelPath);\n } catch (e) {\n this.channelDebug_.dumpException(e, 'Error in running origin trials');\n }\n};\n\n\n/**\n * Cancels backchannel request.\n * @private\n */\nWebChannelBase.prototype.cancelBackChannelRequest_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n this.clearBpDetectionTimer_();\n this.backChannelRequest_.cancel();\n this.backChannelRequest_ = null;\n }\n};\n\n\n/**\n * Cancels all outstanding requests.\n * @private\n */\nWebChannelBase.prototype.cancelRequests_ = function() {\n 'use strict';\n this.cancelBackChannelRequest_();\n\n if (this.backChannelTimerId_) {\n goog.global.clearTimeout(this.backChannelTimerId_);\n this.backChannelTimerId_ = null;\n }\n\n this.clearDeadBackchannelTimer_();\n\n this.forwardChannelRequestPool_.cancel();\n\n if (this.forwardChannelTimerId_) {\n this.clearForwardChannelTimer_();\n }\n};\n\n\n/**\n * Clears the forward channel timer.\n * @private\n */\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\n 'use strict';\n if (typeof this.forwardChannelTimerId_ === 'number') {\n goog.global.clearTimeout(this.forwardChannelTimerId_);\n }\n\n this.forwardChannelTimerId_ = null;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to all the requests sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getExtraHeaders = function() {\n 'use strict';\n return this.extraHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to the init requests\n * sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getInitHeaders = function() {\n 'use strict';\n return this.initHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to the init requests sent to the server.\n *\n * @param {Object} initHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\n 'use strict';\n this.initHeaders_ = initHeaders;\n};\n\n\n/**\n * Sets the URL param name to overwrite custom HTTP headers.\n *\n * @param {string} httpHeadersOverwriteParam The URL param name.\n */\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\n httpHeadersOverwriteParam) {\n 'use strict';\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\n 'use strict';\n this.httpSessionIdParam_ = httpSessionIdParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\n 'use strict';\n return this.httpSessionIdParam_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\n 'use strict';\n this.httpSessionId_ = httpSessionId;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionId = function() {\n 'use strict';\n return this.httpSessionId_;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets whether cross origin requests are supported for the channel.\n *\n * Setting this allows the creation of requests to secondary domains and\n * sends XHRs with the CORS withCredentials bit set to true.\n *\n * In order for cross-origin requests to work, the server will also need to set\n * CORS response headers as per:\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\n */\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\n supportCrossDomain) {\n 'use strict';\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\n};\n\n\n/**\n * Returns the handler used for channel callback events.\n *\n * @return {WebChannelBase.Handler} The handler.\n */\nWebChannelBase.prototype.getHandler = function() {\n 'use strict';\n return this.handler_;\n};\n\n\n/**\n * Sets the handler used for channel callback events.\n * @param {WebChannelBase.Handler} handler The handler to set.\n */\nWebChannelBase.prototype.setHandler = function(handler) {\n 'use strict';\n this.handler_ = handler;\n};\n\n\n/**\n * Returns whether the channel allows the use of a subdomain. There may be\n * cases where this isn't allowed.\n * @return {boolean} Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.getAllowHostPrefix = function() {\n 'use strict';\n return this.allowHostPrefix_;\n};\n\n\n/**\n * Sets whether the channel allows the use of a subdomain. There may be cases\n * where this isn't allowed, for example, logging in with troutboard where\n * using a subdomain causes Apache to force the user to authenticate twice.\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\n 'use strict';\n this.allowHostPrefix_ = allowHostPrefix;\n};\n\n\n/**\n * Returns whether the channel is buffered or not. This may be\n * queried in the WebChannelBase.okToMakeRequest() callback.\n *\n * @return {boolean} Whether the channel is buffered.\n */\nWebChannelBase.prototype.isBuffered = function() {\n 'use strict';\n return !this.enableStreaming_;\n};\n\n\n/**\n * Returns whether streaming mode is allowed. In certain debugging situations,\n * it's useful for the application to have a way to disable streaming mode for a\n * user.\n\n * @return {boolean} Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.getAllowStreamingMode = function() {\n 'use strict';\n return this.allowStreamingMode_;\n};\n\n\n/**\n * Sets whether streaming mode is allowed. In certain debugging situations, it's\n * useful for the application to have a way to disable streaming mode for a\n * user.\n * @param {boolean} allowStreamingMode Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.setAllowStreamingMode = function(allowStreamingMode) {\n 'use strict';\n this.allowStreamingMode_ = allowStreamingMode;\n};\n\n\n/**\n * Sends a request to the server. The format of the request is a Map data\n * structure of key/value pairs. These maps are then encoded in a format\n * suitable for the wire and then reconstituted as a Map data structure that\n * the server can process.\n * @param {!Object|!goog.collections.maps.MapLike} map The map to send.\n * @param {!Object=} opt_context The context associated with the map.\n */\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\n 'use strict';\n goog.asserts.assert(\n this.state_ != WebChannelBase.State.CLOSED,\n 'Invalid operation: sending map when state is closed');\n\n // We can only send 1000 maps per POST, but typically we should never have\n // that much to send, so warn if we exceed that (we still send all the maps).\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\n // severe() is temporary so that we get these uploaded and can figure out\n // what's causing them. Afterwards can change to warning().\n this.channelDebug_.severe(function() {\n 'use strict';\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\n ' queued maps upon queueing ' + goog.json.serialize(map);\n });\n }\n\n this.outgoingMaps_.push(\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\n\n // Messages need be buffered during OPENING to avoid server-side race\n if (this.state_ == WebChannelBase.State.OPENED) {\n this.ensureForwardChannel_();\n }\n};\n\n\n/**\n * When set to true, this changes the behavior of the forward channel so it\n * will not retry requests; it will fail after one network failure, and if\n * there was already one network failure, the request will fail immediately.\n * @param {boolean} failFast Whether or not to fail fast.\n */\nWebChannelBase.prototype.setFailFast = function(failFast) {\n 'use strict';\n this.failFast_ = failFast;\n this.channelDebug_.info('setFailFast: ' + failFast);\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\n this.forwardChannelTimerId_) &&\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\n const self = this;\n this.channelDebug_.info(function() {\n 'use strict';\n return 'Retry count ' + self.forwardChannelRetryCount_ +\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\n '. Fail immediately!';\n });\n\n if (!this.forwardChannelRequestPool_.forceComplete(\n goog.bind(this.onRequestComplete, this))) {\n // i.e., this.forwardChannelTimerId_\n this.clearForwardChannelTimer_();\n // The error code from the last failed request is gone, so just use a\n // generic one.\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n }\n }\n};\n\n\n/**\n * @return {number} The max number of forward-channel retries, which will be 0\n * in fail-fast mode.\n */\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\n 'use strict';\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\n};\n\n\n/**\n * Sets the maximum number of attempts to connect to the server for forward\n * channel requests.\n * @param {number} retries The maximum number of attempts.\n */\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\n 'use strict';\n this.forwardChannelMaxRetries_ = retries;\n};\n\n\n/**\n * Sets the timeout for a forward channel request.\n * @param {number} timeoutMs The timeout in milliseconds.\n */\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\n 'use strict';\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\n};\n\n\n/**\n * @return {number} The max number of back-channel retries, which is a constant.\n */\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\n 'use strict';\n // Back-channel retries is a constant.\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isClosed = function() {\n 'use strict';\n return this.state_ == WebChannelBase.State.CLOSED;\n};\n\n\n/**\n * Returns the channel state.\n * @return {WebChannelBase.State} The current state of the channel.\n */\nWebChannelBase.prototype.getState = function() {\n 'use strict';\n return this.state_;\n};\n\n\n/**\n * @return {number} The last status code received (until `State.CLOSED` is\n * reached).\n */\nWebChannelBase.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * @return {number} The last array id received.\n */\nWebChannelBase.prototype.getLastArrayId = function() {\n 'use strict';\n return this.lastArrayId_;\n};\n\n\n/**\n * Returns whether there are outstanding requests servicing the channel.\n * @return {boolean} true if there are outstanding requests.\n */\nWebChannelBase.prototype.hasOutstandingRequests = function() {\n 'use strict';\n return this.getOutstandingRequests_() != 0;\n};\n\n\n/**\n * Returns the number of outstanding requests.\n * @return {number} The number of outstanding requests to the server.\n * @private\n */\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\n 'use strict';\n let count = 0;\n if (this.backChannelRequest_) {\n count++;\n }\n count += this.forwardChannelRequestPool_.getRequestCount();\n return count;\n};\n\n\n/**\n * Ensures that a forward channel request is scheduled.\n * @private\n */\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.isFull()) {\n // enough connection in process - no need to start a new request\n return;\n }\n\n if (this.forwardChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n this.forwardChannelTimerId_ = true;\n goog.async.run(this.onStartForwardChannelTimer_, this);\n\n this.forwardChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a forward-channel retry for the specified request, unless the max\n * retries has been reached.\n * @param {!ChannelRequest} request The failed request to retry.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() >=\n this.forwardChannelRequestPool_.getMaxSize() -\n (this.forwardChannelTimerId_ ? 1 : 0)) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\n return false;\n }\n\n if (this.forwardChannelTimerId_) {\n this.channelDebug_.debug(\n 'Use the retry request that is already scheduled.');\n this.outgoingMaps_ =\n request.getPendingMessages().concat(this.outgoingMaps_);\n return true;\n }\n\n // No retry for open_() and fail-fast\n if (this.state_ == WebChannelBase.State.INIT ||\n this.state_ == WebChannelBase.State.OPENING ||\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry POST');\n\n this.forwardChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartForwardChannelTimer_, this, request),\n this.getRetryTime_(this.forwardChannelRetryCount_));\n this.forwardChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureForwardChannel\n * @param {ChannelRequest=} opt_retryRequest A failed request\n * to retry.\n * @private\n */\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\n opt_retryRequest) {\n 'use strict';\n // null is possible if scheduled with async.run\n if (this.forwardChannelTimerId_) {\n this.forwardChannelTimerId_ = null;\n this.startForwardChannel_(opt_retryRequest);\n }\n};\n\n\n/**\n * Begins a new forward channel operation to the server.\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\n 'use strict';\n this.channelDebug_.debug('startForwardChannel_');\n if (!this.okToMakeRequest_()) {\n return; // channel is cancelled\n } else if (this.state_ == WebChannelBase.State.INIT) {\n if (opt_retryRequest) {\n this.channelDebug_.severe('Not supposed to retry the open');\n return;\n }\n this.open_();\n this.state_ = WebChannelBase.State.OPENING;\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (opt_retryRequest) {\n this.makeForwardChannelRequest_(opt_retryRequest);\n return;\n }\n\n if (this.outgoingMaps_.length == 0) {\n this.channelDebug_.debug(\n 'startForwardChannel_ returned: ' +\n 'nothing to send');\n // no need to start a new forward channel request\n return;\n }\n\n if (this.forwardChannelRequestPool_.isFull()) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe(\n 'startForwardChannel_ returned: ' +\n 'connection already in progress');\n return;\n }\n\n this.makeForwardChannelRequest_();\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\n }\n};\n\n\n/**\n * Establishes a new channel session with the server.\n * @private\n */\nWebChannelBase.prototype.open_ = function() {\n 'use strict';\n this.channelDebug_.debug('open_()');\n this.nextRid_ = Math.floor(Math.random() * 100000);\n\n const rid = this.nextRid_++;\n const request =\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\n\n // mix the init headers\n let extraHeaders = this.extraHeaders_;\n if (this.initHeaders_) {\n if (extraHeaders) {\n extraHeaders = goog.object.clone(extraHeaders);\n goog.object.extend(extraHeaders, this.initHeaders_);\n } else {\n extraHeaders = this.initHeaders_;\n }\n }\n\n if (this.httpHeadersOverwriteParam_ === null &&\n !this.encodeInitMessageHeaders_) {\n request.setExtraHeaders(extraHeaders);\n extraHeaders = null;\n }\n\n let requestText = this.dequeueOutgoingMaps_(\n request,\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('RID', rid);\n\n if (this.clientVersion_ > 0) {\n uri.setParameterValue('CVER', this.clientVersion_);\n }\n\n // http-session-id to be generated as the response\n if (this.getHttpSessionIdParam()) {\n uri.setParameterValue(\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\n }\n\n this.addAdditionalParams_(uri);\n\n if (extraHeaders) {\n if (this.encodeInitMessageHeaders_) {\n let encodedHeaders =\n httpCors.generateEncodedHttpHeadersOverwriteParam(extraHeaders);\n requestText = 'headers=' + encodedHeaders + '&' + requestText;\n } else if (this.httpHeadersOverwriteParam_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\n } // else - should not happen\n }\n\n this.forwardChannelRequestPool_.addRequest(request);\n\n if (this.blockingHandshake_) {\n uri.setParameterValue('TYPE', 'init'); // default to blocking in future\n }\n\n // Check the option and use GET to enable QUIC 0-RTT\n if (this.fastHandshake_) {\n uri.setParameterValue('$req', requestText);\n\n // enable handshake upgrade\n uri.setParameterValue('SID', 'null');\n request.setDecodeInitialResponse();\n\n request.xmlHttpPost(uri, null, true); // Send as a GET\n } else {\n request.xmlHttpPost(uri, requestText, true);\n }\n};\n\n\n/**\n * @return {number} The number of raw JSON messages to be encoded\n * with the fast-handshake (GET) request, including zero. If messages are not\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\n * @private\n */\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\n 'use strict';\n let total = 0;\n for (let i = 0; i < this.outgoingMaps_.length; i++) {\n const map = this.outgoingMaps_[i];\n const size = map.getRawDataSize();\n if (size === undefined) {\n break;\n }\n total += size;\n\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\n return i;\n }\n\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\n i === this.outgoingMaps_.length - 1) {\n return i + 1;\n }\n }\n\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\n};\n\n\n\n/**\n * Makes a forward channel request using XMLHTTP.\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\n opt_retryRequest) {\n 'use strict';\n let rid;\n if (opt_retryRequest) {\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\n } else {\n rid = this.nextRid_++;\n }\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid,\n this.forwardChannelRetryCount_ + 1);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n request.setExtraHeaders(this.extraHeaders_);\n }\n\n let requestText;\n if (opt_retryRequest) {\n this.requeuePendingMaps_(opt_retryRequest);\n }\n requestText =\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n // Randomize from 50%-100% of the forward channel timeout to avoid\n // a big hit if servers happen to die at once.\n request.setTimeout(\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\n this.forwardChannelRequestPool_.addRequest(request);\n request.xmlHttpPost(uri, requestText, true);\n};\n\n\n/**\n * Adds additional query parameters from `extraParams_` and `handler_` to the\n * given URI.\n * @param {!goog.Uri} uri The URI to add the parameters to.\n * @private\n */\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\n 'use strict';\n if (this.extraParams_) {\n goog.object.forEach(this.extraParams_, function(value, key) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n\n if (this.handler_) {\n const params = this.handler_.getAdditionalParams(this);\n if (params) {\n goog.structs.forEach(params, function(value, key, coll) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n }\n};\n\n\n/**\n * Returns the request text from the outgoing maps and resets it.\n * @param {!ChannelRequest} request The new request for sending the messages.\n * @param {number} maxNum The maximum number of messages to be encoded\n * @return {string} The encoded request text created from all the currently\n * queued outgoing maps.\n * @private\n */\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\n 'use strict';\n const count = Math.min(this.outgoingMaps_.length, maxNum);\n\n const badMapHandler = this.handler_ ?\n goog.bind(this.handler_.badMapError, this.handler_, this) :\n null;\n const result = this.wireCodec_.encodeMessageQueue(\n this.outgoingMaps_, count, badMapHandler);\n\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\n\n return result;\n};\n\n\n/**\n * Requeues unacknowledged sent arrays for retransmission in the next forward\n * channel request.\n * @param {!ChannelRequest} retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\n 'use strict';\n this.outgoingMaps_ =\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\n};\n\n\n/**\n * Ensures there is a backchannel request for receiving data from the server.\n * @private\n */\nWebChannelBase.prototype.ensureBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n // already have one\n return;\n }\n\n if (this.backChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n this.backChannelAttemptId_ = 1;\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n // backChannelTimerId_ stays unset, as with setTimeout(0)\n goog.async.run(this.onStartBackChannelTimer_, this);\n\n this.backChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a back-channel retry, unless the max retries has been reached.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Request already in progress');\n return false;\n }\n\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry GET');\n\n this.backChannelAttemptId_++;\n this.backChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartBackChannelTimer_, this),\n this.getRetryTime_(this.backChannelRetryCount_));\n this.backChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureBackChannel_.\n * @private\n */\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\n 'use strict';\n this.backChannelTimerId_ = null;\n this.startBackChannel_();\n\n if (!this.detectBufferingProxy_) {\n return;\n }\n\n if (this.bpDetectionDone_) {\n return;\n }\n\n if (this.backChannelRequest_ == null || this.handshakeRttMs_ <= 0) {\n this.channelDebug_.warning(\n 'Skip bpDetectionTimerId_ ' + this.backChannelRequest_ + ' ' +\n this.handshakeRttMs_);\n return;\n }\n\n // This goes with each new request until bpDetectionDone_\n const bpDetectionTimeout = 2 * this.handshakeRttMs_;\n this.channelDebug_.info('BP detection timer enabled: ' + bpDetectionTimeout);\n\n this.bpDetectionTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBpDetectionTimer_, this), bpDetectionTimeout);\n};\n\n\n/**\n * Timer callback for bpDetection.\n * @private\n */\nWebChannelBase.prototype.onBpDetectionTimer_ = function() {\n 'use strict';\n if (!this.bpDetectionTimerId_) {\n this.channelDebug_.warning('Invalid operation.');\n return;\n }\n\n this.bpDetectionTimerId_ = null;\n this.channelDebug_.info('BP detection timeout reached.');\n\n goog.asserts.assert(\n this.backChannelRequest_ != null,\n 'Invalid state: no backchannel request');\n\n // We wait for extra response payload in addition to just headers to\n // cancel the timer.\n if (this.backChannelRequest_.getXhr() != null) {\n const responseData = this.backChannelRequest_.getXhr().getResponseText();\n if (responseData) {\n this.channelDebug_.warning(\n 'Timer should have been cancelled : ' + responseData);\n }\n }\n\n // Enable long-polling\n this.channelDebug_.info(\n 'Buffering proxy detected and switch to long-polling!');\n this.enableStreaming_ = false;\n\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\n\n // Cancel the request and start a new one immediately\n this.cancelBackChannelRequest_();\n this.startBackChannel_();\n};\n\n\n/**\n * Clears the timer for BP detection.\n * @private\n */\nWebChannelBase.prototype.clearBpDetectionTimer_ = function() {\n 'use strict';\n if (this.bpDetectionTimerId_ != null) {\n this.channelDebug_.debug('Cancel the BP detection timer.');\n goog.global.clearTimeout(this.bpDetectionTimerId_);\n this.bpDetectionTimerId_ = null;\n }\n};\n\n\n/**\n * Begins a new back channel operation to the server.\n * @private\n */\nWebChannelBase.prototype.startBackChannel_ = function() {\n 'use strict';\n if (!this.okToMakeRequest_()) {\n // channel is cancelled\n return;\n }\n\n this.channelDebug_.debug('Creating new HttpRequest');\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\n }\n\n this.backChannelRequest_.setReadyStateChangeThrottle(\n this.readyStateChangeThrottleMs_);\n const uri = this.backChannelUri_.clone();\n uri.setParameterValue('RID', 'rpc');\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('CI', this.enableStreaming_ ? '0' : '1');\n uri.setParameterValue('AID', this.lastArrayId_);\n uri.setParameterValue('TYPE', 'xmlhttp');\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n if (this.backChannelRequestTimeoutMs_) {\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\n }\n\n this.backChannelRequest_.xmlHttpGet(\n uri, true /* decodeChunks */, this.hostPrefix_);\n\n this.channelDebug_.debug('New Request created');\n};\n\n\n/**\n * Gives the handler a chance to return an error code and stop channel\n * execution. A handler might want to do this to check that the user is still\n * logged in, for example.\n * @private\n * @return {boolean} If it's OK to make a request.\n */\nWebChannelBase.prototype.okToMakeRequest_ = function() {\n 'use strict';\n if (this.handler_) {\n const result = this.handler_.okToMakeRequest(this);\n if (result != WebChannelBase.Error.OK) {\n this.channelDebug_.debug(\n 'Handler returned error code from okToMakeRequest');\n this.signalError_(result);\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onFirstByteReceived = function(request, responseText) {\n 'use strict';\n if (this.backChannelRequest_ == request && this.detectBufferingProxy_) {\n if (!this.bpDetectionDone_) {\n this.channelDebug_.info(\n 'Great, no buffering proxy detected. Bytes received: ' +\n responseText.length);\n goog.asserts.assert(\n this.bpDetectionTimerId_, 'Timer should not have been cancelled.');\n this.clearBpDetectionTimer_();\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\n }\n }\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\n 'use strict';\n if (this.state_ == WebChannelBase.State.CLOSED ||\n (this.backChannelRequest_ != request &&\n !this.forwardChannelRequestPool_.hasRequest(request))) {\n // either CLOSED or a request we don't know about (perhaps an old request)\n return;\n }\n\n // first to check if request has been upgraded to backchannel\n if (!request.isInitialResponseDecoded() &&\n this.forwardChannelRequestPool_.hasRequest(request) &&\n this.state_ == WebChannelBase.State.OPENED) {\n let response;\n try {\n response = this.wireCodec_.decodeMessage(responseText);\n } catch (ex) {\n response = null;\n }\n if (Array.isArray(response) && response.length == 3) {\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\n this.onForwardChannelFlushed_();\n } else {\n this.channelDebug_.debug('Bad POST response data returned');\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\n }\n } else {\n if (request.isInitialResponseDecoded() ||\n this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n }\n\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\n let response = this.wireCodec_.decodeMessage(responseText);\n this.onInput_(/** @type {!Array<?>} */ (response), request);\n }\n }\n};\n\n\n/**\n * Checks if we need call the flush callback.\n *\n * @private\n */\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\n if (this.forwardChannelFlushedCallback_) {\n try {\n this.forwardChannelFlushedCallback_();\n } catch (ex) {\n this.channelDebug_.dumpException(\n ex, 'Exception from forwardChannelFlushedCallback_ ');\n }\n // reset\n this.forwardChannelFlushedCallback_ = undefined;\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server.\n * @param {Array<number>} responseValues The key value pairs in\n * the POST response.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handlePostResponse_ = function(\n responseValues, forwardReq) {\n 'use strict';\n // The first response value is set to 0 if server is missing backchannel.\n if (responseValues[0] == 0) {\n this.handleBackchannelMissing_(forwardReq);\n return;\n }\n this.lastPostResponseArrayId_ = responseValues[1];\n const outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\n if (0 < outstandingArrays) {\n const numOutstandingBackchannelBytes = responseValues[2];\n this.channelDebug_.debug(\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\n ' arrays) are outstanding on the BackChannel');\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\n return;\n }\n if (!this.deadBackChannelTimerId_) {\n // We expect to receive data within 2 RTTs or we retry the backchannel.\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBackChannelDead_, this),\n 2 * WebChannelBase.RTT_ESTIMATE);\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server telling us that it has detected that\n * we have no hanging GET connection.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\n 'use strict';\n // As long as the back channel was started before the POST was sent,\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\n // so as not to excessively retry the backchannel\n this.channelDebug_.debug('Server claims our backchannel is missing.');\n if (this.backChannelTimerId_) {\n this.channelDebug_.debug('But we are currently starting the request.');\n return;\n } else if (!this.backChannelRequest_) {\n this.channelDebug_.warning('We do not have a BackChannel established');\n } else if (\n this.backChannelRequest_.getRequestStartTime() +\n WebChannelBase.RTT_ESTIMATE <\n forwardReq.getRequestStartTime()) {\n this.clearDeadBackchannelTimer_();\n this.cancelBackChannelRequest_();\n } else {\n return;\n }\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\n};\n\n\n/**\n * Determines whether we should start the process of retrying a possibly\n * dead backchannel.\n * @param {number} outstandingBytes The number of bytes for which the server has\n * not yet received acknowledgement.\n * @return {boolean} Whether to start the backchannel retry timer.\n * @private\n */\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\n 'use strict';\n // Not too many outstanding bytes, not buffered and not after a retry.\n return outstandingBytes <\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\n};\n\n\n/**\n * Decides which host prefix should be used, if any. If there is a handler,\n * allows the handler to validate a host prefix provided by the server, and\n * optionally override it.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix to actually use, if any. Will return null\n * if the use of host prefixes was disabled via setAllowHostPrefix().\n * @override\n */\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\n 'use strict';\n if (this.allowHostPrefix_) {\n if (this.handler_) {\n return this.handler_.correctHostPrefix(serverHostPrefix);\n }\n return serverHostPrefix;\n }\n return null;\n};\n\n\n/**\n * Handles the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.onBackChannelDead_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n this.deadBackChannelTimerId_ = null;\n this.cancelBackChannelRequest_();\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\n }\n};\n\n\n/**\n * Clears the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\n this.deadBackChannelTimerId_ = null;\n }\n};\n\n\n/**\n * Returns whether or not the given error/status combination is fatal or not.\n * On fatal errors we immediately close the session rather than retrying the\n * failed request.\n * @param {?ChannelRequest.Error} error The error code for the\n * failed request.\n * @param {number} statusCode The last HTTP status code.\n * @return {boolean} Whether or not the error is fatal.\n * @private\n */\nWebChannelBase.isFatalError_ = function(error, statusCode) {\n 'use strict';\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestComplete = function(request) {\n 'use strict';\n this.channelDebug_.debug('Request complete');\n let type;\n let pendingMessages = null;\n if (this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n this.clearBpDetectionTimer_();\n this.backChannelRequest_ = null;\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\n pendingMessages = request.getPendingMessages();\n this.forwardChannelRequestPool_.removeRequest(request);\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\n } else {\n // return if it was an old request from a previous session\n return;\n }\n\n if (this.state_ == WebChannelBase.State.CLOSED) {\n return;\n }\n\n this.lastStatusCode_ = request.getLastStatusCode();\n\n if (request.getSuccess()) {\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n const size = request.getPostData() ? request.getPostData().length : 0;\n requestStats.notifyTimingEvent(\n size, Date.now() - request.getRequestStartTime(),\n this.forwardChannelRetryCount_);\n this.ensureForwardChannel_();\n this.onSuccess_(request);\n } else { // i.e., back-channel\n this.ensureBackChannel_();\n }\n return;\n }\n // Else unsuccessful. Fall through.\n\n const lastError = request.getLastError();\n if (!WebChannelBase.isFatalError_(lastError, this.lastStatusCode_)) {\n // Maybe retry.\n const self = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'Maybe retrying, last error: ' +\n ChannelRequest.errorStringFromCode(lastError, self.lastStatusCode_);\n });\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n if (this.maybeRetryForwardChannel_(request)) {\n return;\n }\n }\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\n if (this.maybeRetryBackChannel_()) {\n return;\n }\n }\n // Else exceeded max retries. Fall through.\n this.channelDebug_.debug('Exceeded max number of retries');\n } else {\n // Else fatal error. Fall through and mark the pending maps as failed.\n this.channelDebug_.debug('Not retrying due to error type');\n }\n\n\n // Abort the channel now\n\n // Record pending messages from the failed request\n if (pendingMessages && pendingMessages.length > 0) {\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\n }\n\n this.channelDebug_.debug('Error: HTTP request failed');\n switch (lastError) {\n case ChannelRequest.Error.NO_DATA:\n this.signalError_(WebChannelBase.Error.NO_DATA);\n break;\n case ChannelRequest.Error.BAD_DATA:\n this.signalError_(WebChannelBase.Error.BAD_DATA);\n break;\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\n break;\n default:\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n break;\n }\n};\n\n\n/**\n * @param {number} retryCount Number of retries so far.\n * @return {number} Time in ms before firing next retry request.\n * @private\n */\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\n 'use strict';\n let retryTime = this.baseRetryDelayMs_ +\n Math.floor(Math.random() * this.retryDelaySeedMs_);\n if (!this.isActive()) {\n this.channelDebug_.debug('Inactive channel');\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\n }\n // Backoff for subsequent retries\n retryTime *= retryCount;\n return retryTime;\n};\n\n\n/**\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\n * @param {number} delaySeedMs A random delay between 0 and this is added to\n * the base part.\n */\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\n 'use strict';\n this.baseRetryDelayMs_ = baseDelayMs;\n this.retryDelaySeedMs_ = delaySeedMs;\n};\n\n\n/**\n * Apply any handshake control headers.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\n 'use strict';\n const xhr = request.getXhr();\n if (xhr) {\n const clientProtocol =\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\n if (clientProtocol) {\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\n }\n\n if (this.getHttpSessionIdParam()) {\n const httpSessionIdHeader =\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\n if (httpSessionIdHeader) {\n this.setHttpSessionId(httpSessionIdHeader);\n // update the cached uri\n const httpSessionIdParam = this.getHttpSessionIdParam();\n\n this.forwardChannelUri_.setParameterValue(\n /** @type {string} */ (httpSessionIdParam), // never null\n httpSessionIdHeader);\n } else {\n this.channelDebug_.warning(\n 'Missing X_HTTP_SESSION_ID in the handshake response');\n }\n }\n }\n};\n\n\n/**\n * Processes the data returned by the server.\n * @param {!Array<!Array<?>>} respArray The response array returned\n * by the server.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\n 'use strict';\n const batch =\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\n for (let i = 0; i < respArray.length; i++) {\n let nextArray = respArray[i];\n this.lastArrayId_ = nextArray[0];\n nextArray = nextArray[1];\n if (this.state_ == WebChannelBase.State.OPENING) {\n if (nextArray[0] == 'c') {\n this.sid_ = nextArray[1];\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\n\n const negotiatedVersion = nextArray[3];\n if (negotiatedVersion != null) {\n this.channelVersion_ = negotiatedVersion;\n this.channelDebug_.info('VER=' + this.channelVersion_);\n }\n\n const negotiatedServerVersion = nextArray[4];\n if (negotiatedServerVersion != null) {\n this.serverVersion_ = negotiatedServerVersion;\n this.channelDebug_.info('SVER=' + this.serverVersion_);\n }\n\n // CVER=22\n const serverKeepaliveMs = nextArray[5];\n if (serverKeepaliveMs != null &&\n typeof serverKeepaliveMs === 'number' && serverKeepaliveMs > 0) {\n const timeout = 1.5 * serverKeepaliveMs;\n this.backChannelRequestTimeoutMs_ = timeout;\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\n }\n\n this.applyControlHeaders_(request);\n\n this.state_ = WebChannelBase.State.OPENED;\n if (this.handler_) {\n this.handler_.channelOpened(this);\n }\n\n if (this.detectBufferingProxy_) {\n this.handshakeRttMs_ = Date.now() - request.getRequestStartTime();\n this.channelDebug_.info(\n 'Handshake RTT: ' + this.handshakeRttMs_ + 'ms');\n }\n\n this.startBackchannelAfterHandshake_(request);\n\n if (this.outgoingMaps_.length > 0) {\n this.ensureForwardChannel_();\n }\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n // treat close also as an abort\n this.signalError_(WebChannelBase.Error.STOP);\n }\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n batch.length = 0;\n }\n if (nextArray[0] == 'stop') {\n this.signalError_(WebChannelBase.Error.STOP);\n } else {\n this.disconnect();\n }\n } else if (nextArray[0] == 'noop') {\n // ignore - noop to keep connection happy\n } else {\n if (batch) {\n batch.push(nextArray);\n } else if (this.handler_) {\n this.handler_.channelHandleArray(this, nextArray);\n }\n }\n // We have received useful data on the back-channel, so clear its retry\n // count. We do this because back-channels by design do not complete\n // quickly, so on a flaky connection we could have many fail to complete\n // fully but still deliver a lot of data before they fail. We don't want\n // to count such failures towards the retry limit, because we don't want\n // to give up on a session if we can still receive data.\n this.backChannelRetryCount_ = 0;\n }\n }\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n }\n};\n\n\n/**\n * Starts the backchannel after the handshake.\n *\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\n 'use strict';\n this.backChannelUri_ = this.getBackChannelUri(\n this.hostPrefix_, /** @type {string} */ (this.path_));\n\n if (request.isInitialResponseDecoded()) {\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\n this.forwardChannelRequestPool_.removeRequest(request);\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\n this.backChannelRequest_ = request;\n } else {\n this.ensureBackChannel_();\n }\n};\n\n\n/**\n * Helper to ensure the channel is in the expected state.\n * @param {...number} var_args The channel must be in one of the indicated\n * states.\n * @private\n */\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\n 'use strict';\n goog.asserts.assert(\n goog.array.contains(arguments, this.state_),\n 'Unexpected channel state: %s', this.state_);\n};\n\n\n/**\n * Signals an error has occurred.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.signalError_ = function(error) {\n 'use strict';\n this.channelDebug_.info('Error code ' + error);\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\n // Create a separate Internet connection to check\n // if it's a server error or user's network error.\n let imageUri = null;\n if (this.handler_) {\n imageUri = this.handler_.getNetworkTestImageUri(this);\n }\n netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);\n } else {\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n }\n this.onError_(error);\n};\n\n\n/**\n * Callback for netUtils.testNetwork during error handling.\n * @param {boolean} networkUp Whether the network is up.\n * @private\n */\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\n 'use strict';\n if (networkUp) {\n this.channelDebug_.info('Successfully pinged google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n } else {\n this.channelDebug_.info('Failed to ping google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\n // Do not call onError_ again to eliminate duplicated Error events.\n }\n};\n\n\n/**\n * Called when messages have been successfully sent from the queue.\n * @param {!ChannelRequest} request The request object\n * @private\n */\nWebChannelBase.prototype.onSuccess_ = function(request) {\n 'use strict';\n if (this.handler_) {\n this.handler_.channelSuccess(this, request);\n }\n};\n\n\n/**\n * Called when we've determined the final error for a channel. It closes the\n * notifiers the handler of the error and closes the channel.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.onError_ = function(error) {\n 'use strict';\n this.channelDebug_.debug('HttpChannel: error - ' + error);\n this.state_ = WebChannelBase.State.CLOSED;\n if (this.handler_) {\n this.handler_.channelError(this, error);\n }\n this.onClose_();\n this.cancelRequests_();\n};\n\n\n/**\n * Called when the channel has been closed. It notifiers the handler of the\n * event, and reports any pending or undelivered maps.\n * @private\n */\nWebChannelBase.prototype.onClose_ = function() {\n 'use strict';\n this.state_ = WebChannelBase.State.CLOSED;\n this.nonAckedMapsAtChannelClose_ = [];\n if (this.handler_) {\n const pendingMessages =\n this.forwardChannelRequestPool_.getPendingMessages();\n\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\n this.handler_.channelClosed(this);\n } else {\n this.channelDebug_.debug(\n () => 'Number of undelivered maps' +\n ', pending: ' + pendingMessages.length +\n ', outgoing: ' + this.outgoingMaps_.length);\n\n goog.array.extend(this.nonAckedMapsAtChannelClose_, pendingMessages);\n goog.array.extend(this.nonAckedMapsAtChannelClose_, this.outgoingMaps_);\n\n this.forwardChannelRequestPool_.clearPendingMessages();\n\n const copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\n this.outgoingMaps_.length = 0;\n\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\n }\n }\n};\n\n/**\n * @return {!Array<!Wire.QueuedMap>} Returns the list of non-acked maps, both\n * during an active channel or after the channel is closed. Refer to the\n * `getNonAckedMessages()` API for definitions of non-acked messages.\n */\nWebChannelBase.prototype.getNonAckedMaps = function() {\n if (this.state_ == WebChannelBase.State.CLOSED) {\n goog.asserts.assert(\n this.nonAckedMapsAtChannelClose_ != null,\n 'nonAckedMapsAtChannelClose_ is not set after channel close.');\n return this.nonAckedMapsAtChannelClose_;\n }\n\n // The underlying message objects are not cloned and thus exposes a mutability\n // risk, but is chosen to make strict equality (i.e. ===) checks possible for\n // callers.\n let unAckedMaps = [];\n goog.array.extend(\n unAckedMaps, this.forwardChannelRequestPool_.getPendingMessages());\n goog.array.extend(unAckedMaps, this.outgoingMaps_);\n\n return unAckedMaps;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\n 'use strict';\n const uri = this.createDataUri(null, path);\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getConnectionState = function() {\n 'use strict';\n return this.connState_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\n 'use strict';\n const uri = this.createDataUri(\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.createDataUri = function(\n hostPrefix, path, opt_overridePort) {\n 'use strict';\n let uri = goog.Uri.parse(path);\n const uriAbsolute = (uri.getDomain() != '');\n if (uriAbsolute) {\n if (hostPrefix) {\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\n }\n\n uri.setPort(opt_overridePort || uri.getPort());\n } else {\n const locationPage = goog.global.location;\n let hostName;\n if (hostPrefix) {\n hostName = hostPrefix + '.' + locationPage.hostname;\n } else {\n hostName = locationPage.hostname;\n }\n\n const port = opt_overridePort || +locationPage.port;\n\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\n }\n\n const param = this.getHttpSessionIdParam();\n const value = this.getHttpSessionId();\n if (param && value) {\n uri.setParameterValue(param, value);\n }\n\n // Add the protocol version to the URI.\n uri.setParameterValue('VER', this.channelVersion_);\n\n this.addAdditionalParams_(uri);\n\n return uri;\n};\n\n/**\n * @override\n * @param {?string} hostPrefix The host prefix, if we need an XhrIo object\n * capable of calling a secondary domain.\n * @param {boolean=} isStreaming Whether or not fetch/streams are enabled for\n * the underlying HTTP request.\n * @return {!goog.net.XhrIo} A new XhrIo object.\n */\nWebChannelBase.prototype.createXhrIo = function(hostPrefix, isStreaming) {\n 'use strict';\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\n }\n let xhr;\n if (isStreaming && this.usesFetchStreams_ && !this.xmlHttpFactory_) {\n xhr = new goog.net.XhrIo(\n new goog.net.FetchXmlHttpFactory({streamBinaryChunks: true}));\n } else {\n xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\n }\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\n return xhr;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isActive = function() {\n 'use strict';\n return !!this.handler_ && this.handler_.isActive(this);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\n 'use strict';\n return this.supportsCrossDomainXhrs_;\n};\n\n\n/**\n * Sets (overwrites) the forward channel flush callback.\n *\n * @param {function()} callback The callback to be invoked.\n */\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\n 'use strict';\n this.forwardChannelFlushedCallback_ = callback;\n};\n\n\n/**\n * Abstract base class for the channel handler\n * @constructor\n * @struct\n */\nWebChannelBase.Handler = function() {};\n\n\n/**\n * Callback handler for when a batch of response arrays is received from the\n * server. When null, batched dispatching is disabled.\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\n */\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\n\n\n/**\n * Whether it's okay to make a request to the server. A handler can return\n * false if the channel should fail. For example, if the user has logged out,\n * the handler may want all requests to fail immediately.\n * @param {WebChannelBase} channel The channel.\n * @return {WebChannelBase.Error} An error code. The code should\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\n * error code will cause a failure.\n */\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\n 'use strict';\n return WebChannelBase.Error.OK;\n};\n\n\n/**\n * Indicates the WebChannel has successfully negotiated with the server\n * and can now send and receive data.\n * @param {WebChannelBase} channel The channel.\n */\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\n\n\n/**\n * New input is available for the application to process.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {Array<?>} array The data array.\n */\nWebChannelBase.Handler.prototype.channelHandleArray = function(\n channel, array) {};\n\n\n/**\n * Indicates messages that have been successfully sent on the channel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!ChannelRequest} request The request object that contains\n * the pending messages that have been successfully delivered to the server.\n */\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\n\n\n/**\n * Indicates an error occurred on the WebChannel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {WebChannelBase.Error} error The error code.\n */\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\n\n\n/**\n * Indicates the WebChannel is closed. Also notifies about which maps,\n * if any, that may not have been delivered to the server.\n * @param {WebChannelBase} channel The channel.\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\n * array of pending maps, which may or may not have been delivered to the\n * server.\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\n * The array of undelivered maps, which have definitely not been delivered\n * to the server.\n */\nWebChannelBase.Handler.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\n\n\n/**\n * Gets any parameters that should be added at the time another connection is\n * made to the server.\n * @param {WebChannelBase} channel The channel.\n * @return {!Object} Extra parameter keys and values to add to the requests.\n */\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\n 'use strict';\n return {};\n};\n\n\n/**\n * Gets the URI of an image that can be used to test network connectivity.\n * @param {WebChannelBase} channel The channel.\n * @return {goog.Uri?} A custom URI to load for the network test.\n */\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\n 'use strict';\n return null;\n};\n\n\n/**\n * Gets whether this channel is currently active. This is used to determine the\n * length of time to wait before retrying.\n * @param {WebChannelBase} channel The channel.\n * @return {boolean} Whether the channel is currently active.\n */\nWebChannelBase.Handler.prototype.isActive = function(channel) {\n 'use strict';\n return true;\n};\n\n/**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @override\n * @return {boolean}\n */\nWebChannelBase.prototype.usesFetchStreams = function() {\n 'use strict';\n return this.usesFetchStreams_;\n};\n\n\n/**\n * Called by the channel if enumeration of the map throws an exception.\n * @param {WebChannelBase} channel The channel.\n * @param {Object} map The map that can't be enumerated.\n */\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\n\n\n/**\n * Allows the handler to override a host prefix provided by the server. Will\n * be called whenever the channel has received such a prefix and is considering\n * its use.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix the client should use.\n */\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\n serverHostPrefix) {\n 'use strict';\n return serverHostPrefix;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class for parsing and formatting URIs.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\n * create a new instance of the goog.Uri object from Uri parts.\n *\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\n *\n * Implements RFC 3986 for parsing/formatting URIs.\n * http://www.ietf.org/rfc/rfc3986.txt\n *\n * Some changes have been made to the interface (more like .NETs), though the\n * internal representation is now of un-encoded parts, this will change the\n * behavior slightly.\n */\n\ngoog.provide('goog.Uri');\ngoog.provide('goog.Uri.QueryData');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.string');\ngoog.require('goog.structs');\ngoog.require('goog.uri.utils');\ngoog.require('goog.uri.utils.ComponentIndex');\ngoog.require('goog.uri.utils.StandardQueryParam');\n\n\n\n/**\n * This class contains setters and getters for the parts of the URI.\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\n * decoded path, <code>/foo bar</code>.\n *\n * Reserved characters (see RFC 3986 section 2.2) can be present in\n * their percent-encoded form in scheme, domain, and path URI components and\n * will not be auto-decoded. For example:\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\n * return <code>relative/path%2fto/resource</code>.\n *\n * The constructor accepts an optional unparsed, raw URI string. The parser\n * is relaxed, so special characters that aren't escaped but don't cause\n * ambiguities will not cause parse failures.\n *\n * All setters return <code>this</code> and so may be chained, a la\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\n *\n * @param {*=} opt_uri Optional string URI to parse\n * (use goog.Uri.create() to create a URI from parts), or if\n * a goog.Uri is passed, a clone is created.\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\n * the case of the parameter name.\n *\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\n * if decodeURIComponent fails on any of the URI components).\n * @constructor\n * @struct\n */\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\n 'use strict';\n /**\n * Scheme such as \"http\".\n * @private {string}\n */\n this.scheme_ = '';\n\n /**\n * User credentials in the form \"username:password\".\n * @private {string}\n */\n this.userInfo_ = '';\n\n /**\n * Domain part, e.g. \"www.google.com\".\n * @private {string}\n */\n this.domain_ = '';\n\n /**\n * Port, e.g. 8080.\n * @private {?number}\n */\n this.port_ = null;\n\n /**\n * Path, e.g. \"/tests/img.png\".\n * @private {string}\n */\n this.path_ = '';\n\n /**\n * The fragment without the #.\n * @private {string}\n */\n this.fragment_ = '';\n\n /**\n * Whether or not this Uri should be treated as Read Only.\n * @private {boolean}\n */\n this.isReadOnly_ = false;\n\n /**\n * Whether or not to ignore case when comparing query params.\n * @private {boolean}\n */\n this.ignoreCase_ = false;\n\n /**\n * Object representing query data.\n * @private {!goog.Uri.QueryData}\n */\n this.queryData_;\n\n // Parse in the uri string\n var m;\n if (opt_uri instanceof goog.Uri) {\n this.ignoreCase_ = (opt_ignoreCase !== undefined) ? opt_ignoreCase :\n opt_uri.getIgnoreCase();\n this.setScheme(opt_uri.getScheme());\n this.setUserInfo(opt_uri.getUserInfo());\n this.setDomain(opt_uri.getDomain());\n this.setPort(opt_uri.getPort());\n this.setPath(opt_uri.getPath());\n this.setQueryData(opt_uri.getQueryData().clone());\n this.setFragment(opt_uri.getFragment());\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\n this.ignoreCase_ = !!opt_ignoreCase;\n\n // Set the parts -- decoding as we do so.\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\n // whereas in other browsers they will be undefined.\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\n\n } else {\n this.ignoreCase_ = !!opt_ignoreCase;\n this.queryData_ = new goog.Uri.QueryData(null, this.ignoreCase_);\n }\n};\n\n\n/**\n * Parameter name added to stop caching.\n * @type {string}\n */\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\n\n\n/**\n * @return {string} The string form of the url.\n * @override\n */\ngoog.Uri.prototype.toString = function() {\n 'use strict';\n var out = [];\n\n var scheme = this.getScheme();\n if (scheme) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n ':');\n }\n\n var domain = this.getDomain();\n if (domain || scheme == 'file') {\n out.push('//');\n\n var userInfo = this.getUserInfo();\n if (userInfo) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n '@');\n }\n\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\n\n var port = this.getPort();\n if (port != null) {\n out.push(':', String(port));\n }\n }\n\n var path = this.getPath();\n if (path) {\n if (this.hasDomain() && path.charAt(0) != '/') {\n out.push('/');\n }\n out.push(goog.Uri.encodeSpecialChars_(\n path,\n path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\n goog.Uri.reDisallowedInRelativePath_,\n true));\n }\n\n var query = this.getEncodedQuery();\n if (query) {\n out.push('?', query);\n }\n\n var fragment = this.getFragment();\n if (fragment) {\n out.push(\n '#',\n goog.Uri.encodeSpecialChars_(\n fragment, goog.Uri.reDisallowedInFragment_));\n }\n return out.join('');\n};\n\n\n/**\n * Resolves the given relative URI (a goog.Uri object), using the URI\n * represented by this instance as the base URI.\n *\n * There are several kinds of relative URIs:<br>\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\n * 2. /foo - replaces the path, the query and fragment<br>\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\n * 4. ?foo - replace the query and fragment<br>\n * 5. #foo - replace the fragment only\n *\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\n * segments will be resolved, as described in RFC 3986.\n *\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\n * @return {!goog.Uri} The resolved URI.\n */\ngoog.Uri.prototype.resolve = function(relativeUri) {\n 'use strict';\n var absoluteUri = this.clone();\n\n // we satisfy these conditions by looking for the first part of relativeUri\n // that is not blank and applying defaults to the rest\n\n var overridden = relativeUri.hasScheme();\n\n if (overridden) {\n absoluteUri.setScheme(relativeUri.getScheme());\n } else {\n overridden = relativeUri.hasUserInfo();\n }\n\n if (overridden) {\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\n } else {\n overridden = relativeUri.hasDomain();\n }\n\n if (overridden) {\n absoluteUri.setDomain(relativeUri.getDomain());\n } else {\n overridden = relativeUri.hasPort();\n }\n\n var path = relativeUri.getPath();\n if (overridden) {\n absoluteUri.setPort(relativeUri.getPort());\n } else {\n overridden = relativeUri.hasPath();\n if (overridden) {\n // resolve path properly\n if (path.charAt(0) != '/') {\n // path is relative\n if (this.hasDomain() && !this.hasPath()) {\n // RFC 3986, section 5.2.3, case 1\n path = '/' + path;\n } else {\n // RFC 3986, section 5.2.3, case 2\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\n if (lastSlashIndex != -1) {\n path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;\n }\n }\n }\n path = goog.Uri.removeDotSegments(path);\n }\n }\n\n if (overridden) {\n absoluteUri.setPath(path);\n } else {\n overridden = relativeUri.hasQuery();\n }\n\n if (overridden) {\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\n } else {\n overridden = relativeUri.hasFragment();\n }\n\n if (overridden) {\n absoluteUri.setFragment(relativeUri.getFragment());\n }\n\n return absoluteUri;\n};\n\n\n/**\n * Clones the URI instance.\n * @return {!goog.Uri} New instance of the URI object.\n */\ngoog.Uri.prototype.clone = function() {\n 'use strict';\n return new goog.Uri(this);\n};\n\n\n/**\n * @return {string} The encoded scheme/protocol for the URI.\n */\ngoog.Uri.prototype.getScheme = function() {\n 'use strict';\n return this.scheme_;\n};\n\n\n/**\n * Sets the scheme/protocol.\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newScheme New scheme value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.scheme_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\n\n // remove an : at the end of the scheme so somebody can pass in\n // window.location.protocol\n if (this.scheme_) {\n this.scheme_ = this.scheme_.replace(/:$/, '');\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the scheme has been set.\n */\ngoog.Uri.prototype.hasScheme = function() {\n 'use strict';\n return !!this.scheme_;\n};\n\n\n/**\n * @return {string} The decoded user info.\n */\ngoog.Uri.prototype.getUserInfo = function() {\n 'use strict';\n return this.userInfo_;\n};\n\n\n/**\n * Sets the userInfo.\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newUserInfo New userInfo value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.userInfo_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the user info has been set.\n */\ngoog.Uri.prototype.hasUserInfo = function() {\n 'use strict';\n return !!this.userInfo_;\n};\n\n\n/**\n * @return {string} The decoded domain.\n */\ngoog.Uri.prototype.getDomain = function() {\n 'use strict';\n return this.domain_;\n};\n\n\n/**\n * Sets the domain.\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newDomain New domain value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.domain_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the domain has been set.\n */\ngoog.Uri.prototype.hasDomain = function() {\n 'use strict';\n return !!this.domain_;\n};\n\n\n/**\n * @return {?number} The port number.\n */\ngoog.Uri.prototype.getPort = function() {\n 'use strict';\n return this.port_;\n};\n\n\n/**\n * Sets the port number.\n * @param {*} newPort Port number. Will be explicitly casted to a number.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPort = function(newPort) {\n 'use strict';\n this.enforceReadOnly();\n\n if (newPort) {\n newPort = Number(newPort);\n if (isNaN(newPort) || newPort < 0) {\n throw new Error('Bad port number ' + newPort);\n }\n this.port_ = newPort;\n } else {\n this.port_ = null;\n }\n\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the port has been set.\n */\ngoog.Uri.prototype.hasPort = function() {\n 'use strict';\n return this.port_ != null;\n};\n\n\n/**\n * @return {string} The decoded path.\n */\ngoog.Uri.prototype.getPath = function() {\n 'use strict';\n return this.path_;\n};\n\n\n/**\n * Sets the path.\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newPath New path value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the path has been set.\n */\ngoog.Uri.prototype.hasPath = function() {\n 'use strict';\n return !!this.path_;\n};\n\n\n/**\n * @return {boolean} Whether the query string has been set.\n */\ngoog.Uri.prototype.hasQuery = function() {\n 'use strict';\n return this.queryData_.toString() !== '';\n};\n\n\n/**\n * Sets the query data.\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * Applies only if queryData is a string.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n\n if (queryData instanceof goog.Uri.QueryData) {\n this.queryData_ = queryData;\n this.queryData_.setIgnoreCase(this.ignoreCase_);\n } else {\n if (!opt_decode) {\n // QueryData accepts encoded query string, so encode it if\n // opt_decode flag is not true.\n queryData = goog.Uri.encodeSpecialChars_(\n queryData, goog.Uri.reDisallowedInQuery_);\n }\n this.queryData_ = new goog.Uri.QueryData(queryData, this.ignoreCase_);\n }\n\n return this;\n};\n\n\n/**\n * Sets the URI query.\n * @param {string} newQuery New query value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\n 'use strict';\n return this.setQueryData(newQuery, opt_decode);\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getEncodedQuery = function() {\n 'use strict';\n return this.queryData_.toString();\n};\n\n\n/**\n * @return {string} The decoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getDecodedQuery = function() {\n 'use strict';\n return this.queryData_.toDecodedString();\n};\n\n\n/**\n * Returns the query data.\n * @return {!goog.Uri.QueryData} QueryData object.\n */\ngoog.Uri.prototype.getQueryData = function() {\n 'use strict';\n return this.queryData_;\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n *\n * Warning: This method, unlike other getter methods, returns encoded\n * value, instead of decoded one.\n */\ngoog.Uri.prototype.getQuery = function() {\n 'use strict';\n return this.getEncodedQuery();\n};\n\n\n/**\n * Sets the value of the named query parameters, clearing previous values for\n * that key.\n *\n * @param {string} key The parameter to set.\n * @param {*} value The new value. Value does not need to be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValue = function(key, value) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.set(key, value);\n return this;\n};\n\n\n/**\n * Sets the values of the named query parameters, clearing previous values for\n * that key. Not new values will currently be moved to the end of the query\n * string.\n *\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\n *\n * @param {string} key The parameter to set.\n * @param {*} values The new values. If values is a single\n * string then it will be treated as the sole value. Values do not need to\n * be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValues = function(key, values) {\n 'use strict';\n this.enforceReadOnly();\n\n if (!Array.isArray(values)) {\n values = [String(values)];\n }\n\n this.queryData_.setValues(key, values);\n\n return this;\n};\n\n\n/**\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\n * query parameter values.\n * @param {string} name The parameter to get values for.\n * @return {!Array<?>} The values for a given cgi parameter as a list of\n * decoded query parameter values.\n */\ngoog.Uri.prototype.getParameterValues = function(name) {\n 'use strict';\n return this.queryData_.getValues(name);\n};\n\n\n/**\n * Returns the first value for a given cgi parameter or undefined if the given\n * parameter name does not appear in the query string.\n * @param {string} paramName Unescaped parameter name.\n * @return {string|undefined} The first value for a given cgi parameter or\n * undefined if the given parameter name does not appear in the query\n * string.\n */\ngoog.Uri.prototype.getParameterValue = function(paramName) {\n 'use strict';\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\n};\n\n\n/**\n * @return {string} The URI fragment, not including the #.\n */\ngoog.Uri.prototype.getFragment = function() {\n 'use strict';\n return this.fragment_;\n};\n\n\n/**\n * Sets the URI fragment.\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newFragment New fragment value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.fragment_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI has a fragment set.\n */\ngoog.Uri.prototype.hasFragment = function() {\n 'use strict';\n return !!this.fragment_;\n};\n\n\n/**\n * Returns true if this has the same domain as that of uri2.\n * @param {!goog.Uri} uri2 The URI object to compare to.\n * @return {boolean} true if same domain; false otherwise.\n */\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\n 'use strict';\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\n this.getDomain() == uri2.getDomain()) &&\n ((!this.hasPort() && !uri2.hasPort()) ||\n this.getPort() == uri2.getPort());\n};\n\n\n/**\n * Adds a random parameter to the Uri.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.makeUnique = function() {\n 'use strict';\n this.enforceReadOnly();\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\n\n return this;\n};\n\n\n/**\n * Removes the named query parameter.\n *\n * @param {string} key The parameter to remove.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.removeParameter = function(key) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.remove(key);\n return this;\n};\n\n\n/**\n * Sets whether Uri is read only. If this goog.Uri is read-only,\n * enforceReadOnly_ will be called at the start of any function that may modify\n * this Uri.\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\n 'use strict';\n this.isReadOnly_ = isReadOnly;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI is read only.\n */\ngoog.Uri.prototype.isReadOnly = function() {\n 'use strict';\n return this.isReadOnly_;\n};\n\n\n/**\n * Checks if this Uri has been marked as read only, and if so, throws an error.\n * This should be called whenever any modifying function is called.\n */\ngoog.Uri.prototype.enforceReadOnly = function() {\n 'use strict';\n if (this.isReadOnly_) {\n throw new Error('Tried to modify a read-only Uri');\n }\n};\n\n\n/**\n * Sets whether to ignore case.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n this.ignoreCase_ = ignoreCase;\n if (this.queryData_) {\n this.queryData_.setIgnoreCase(ignoreCase);\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether to ignore case.\n */\ngoog.Uri.prototype.getIgnoreCase = function() {\n 'use strict';\n return this.ignoreCase_;\n};\n\n\n//==============================================================================\n// Static members\n//==============================================================================\n\n\n/**\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\n * If a Uri object is passed to parse then it will return a clone of the object.\n *\n * @throws URIError If parsing the URI is malformed. The passed URI components\n * should all be parseable by decodeURIComponent.\n * @param {*} uri Raw URI string or instance of Uri\n * object.\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\n * names in #getParameterValue.\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\n 'use strict';\n return uri instanceof goog.Uri ? uri.clone() :\n new goog.Uri(uri, opt_ignoreCase);\n};\n\n\n/**\n * Creates a new goog.Uri object from unencoded parts.\n *\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\n * @param {?string=} opt_userInfo username:password.\n * @param {?string=} opt_domain www.google.com.\n * @param {?number=} opt_port 9830.\n * @param {?string=} opt_path /some/path/to/a/file.html.\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\n * @param {?string=} opt_fragment The fragment without the #.\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\n * #getParameterValue.\n *\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.create = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\n opt_fragment, opt_ignoreCase) {\n 'use strict';\n var uri = new goog.Uri(null, opt_ignoreCase);\n\n // Only set the parts if they are defined and not empty strings.\n opt_scheme && uri.setScheme(opt_scheme);\n opt_userInfo && uri.setUserInfo(opt_userInfo);\n opt_domain && uri.setDomain(opt_domain);\n opt_port && uri.setPort(opt_port);\n opt_path && uri.setPath(opt_path);\n opt_query && uri.setQueryData(opt_query);\n opt_fragment && uri.setFragment(opt_fragment);\n\n return uri;\n};\n\n\n/**\n * Resolves a relative Uri against a base Uri, accepting both strings and\n * Uri objects.\n *\n * @param {*} base Base Uri.\n * @param {*} rel Relative Uri.\n * @return {!goog.Uri} Resolved uri.\n */\ngoog.Uri.resolve = function(base, rel) {\n 'use strict';\n if (!(base instanceof goog.Uri)) {\n base = goog.Uri.parse(base);\n }\n\n if (!(rel instanceof goog.Uri)) {\n rel = goog.Uri.parse(rel);\n }\n\n return base.resolve(rel);\n};\n\n\n/**\n * Removes dot segments in given path component, as described in\n * RFC 3986, section 5.2.4.\n *\n * @param {string} path A non-empty path component.\n * @return {string} Path component with removed dot segments.\n */\ngoog.Uri.removeDotSegments = function(path) {\n 'use strict';\n if (path == '..' || path == '.') {\n return '';\n\n } else if (\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\n // This optimization detects uris which do not contain dot-segments,\n // and as a consequence do not require any processing.\n return path;\n\n } else {\n var leadingSlash = goog.string.startsWith(path, '/');\n var segments = path.split('/');\n var out = [];\n\n for (var pos = 0; pos < segments.length;) {\n var segment = segments[pos++];\n\n if (segment == '.') {\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else if (segment == '..') {\n if (out.length > 1 || out.length == 1 && out[0] != '') {\n out.pop();\n }\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else {\n out.push(segment);\n leadingSlash = true;\n }\n }\n\n return out.join('/');\n }\n};\n\n\n/**\n * Decodes a value or returns the empty string if it isn't defined or empty.\n * @throws URIError If decodeURIComponent fails to decode val.\n * @param {string|undefined} val Value to decode.\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\n * not be decoded.\n * @return {string} Decoded value.\n * @private\n */\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\n 'use strict';\n // Don't use UrlDecode() here because val is not a query parameter.\n if (!val) {\n return '';\n }\n\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\n // so that we can distinguish between the 2 inputs. This is later undone by\n // removeDoubleEncoding_.\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\n decodeURIComponent(val);\n};\n\n\n/**\n * If unescapedPart is non null, then escapes any characters in it that aren't\n * valid characters in a url and also escapes any special characters that\n * appear in extra.\n *\n * @param {*} unescapedPart The string to encode.\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\n * encoding.\n * @return {?string} null iff unescapedPart == null.\n * @private\n */\ngoog.Uri.encodeSpecialChars_ = function(\n unescapedPart, extra, opt_removeDoubleEncoding) {\n 'use strict';\n if (typeof unescapedPart === 'string') {\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\n if (opt_removeDoubleEncoding) {\n // encodeURI double-escapes %XX sequences used to represent restricted\n // characters in some URI components, remove the double escaping here.\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\n }\n return encoded;\n }\n return null;\n};\n\n\n/**\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\n * @param {string} ch One character string.\n * @return {string} Encoded string.\n * @private\n */\ngoog.Uri.encodeChar_ = function(ch) {\n 'use strict';\n var n = ch.charCodeAt(0);\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\n};\n\n\n/**\n * Removes double percent-encoding from a string.\n * @param {string} doubleEncodedString String\n * @return {string} String with double encoding removed.\n * @private\n */\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\n 'use strict';\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\n};\n\n\n/**\n * Regular expression for characters that are disallowed in the scheme or\n * userInfo part of the URI.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in a relative path.\n * Colon is included due to RFC 3986 3.3.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in an absolute path.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the query.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the fragment.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInFragment_ = /#/g;\n\n\n/**\n * Checks whether two URIs have the same domain.\n * @param {string} uri1String First URI string.\n * @param {string} uri2String Second URI string.\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\n */\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\n 'use strict';\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\n var pieces1 = goog.uri.utils.split(uri1String);\n var pieces2 = goog.uri.utils.split(uri2String);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n\n/**\n * Class used to represent URI query parameters. It is essentially a hash of\n * name-value pairs, though a name can be present more than once.\n *\n * Has the same interface as the collections in goog.structs.\n *\n * @param {?string=} opt_query Optional encoded query string to parse into\n * the object.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @constructor\n * @struct\n * @final\n */\ngoog.Uri.QueryData = function(opt_query, opt_ignoreCase) {\n 'use strict';\n /**\n * The map containing name/value or name/array-of-values pairs.\n * May be null if it requires parsing from the query string.\n *\n * We need to use a Map because we cannot guarantee that the key names will\n * not be problematic for IE.\n *\n * @private {?Map<string, !Array<*>>}\n */\n this.keyMap_ = null;\n\n /**\n * The number of params, or null if it requires computing.\n * @private {?number}\n */\n this.count_ = null;\n\n /**\n * Encoded query string, or null if it requires computing from the key map.\n * @private {?string}\n */\n this.encodedQuery_ = opt_query || null;\n\n /**\n * If true, ignore the case of the parameter name in #get.\n * @private {boolean}\n */\n this.ignoreCase_ = !!opt_ignoreCase;\n};\n\n\n/**\n * If the underlying key map is not yet initialized, it parses the\n * query string and fills the map with parsed data.\n * @private\n */\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\n 'use strict';\n if (!this.keyMap_) {\n this.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map());\n this.count_ = 0;\n if (this.encodedQuery_) {\n var self = this;\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\n 'use strict';\n self.add(goog.string.urlDecode(name), value);\n });\n }\n }\n};\n\n\n/**\n * Creates a new query data instance from a map of names and values.\n *\n * @param {!goog.collections.maps.MapLike<string, ?>|!Object} map Map of string\n * parameter names to parameter value. If parameter value is an array, it is\n * treated as if the key maps to each individual value in the\n * array.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromMap = function(map, opt_ignoreCase) {\n 'use strict';\n var keys = goog.structs.getKeys(map);\n if (typeof keys == 'undefined') {\n throw new Error('Keys are undefined');\n }\n\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n var values = goog.structs.getValues(map);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = values[i];\n if (!Array.isArray(value)) {\n queryData.add(key, value);\n } else {\n queryData.setValues(key, value);\n }\n }\n return queryData;\n};\n\n\n/**\n * Creates a new query data instance from parallel arrays of parameter names\n * and values. Allows for duplicate parameter names. Throws an error if the\n * lengths of the arrays differ.\n *\n * @param {!Array<string>} keys Parameter names.\n * @param {!Array<?>} values Parameter values.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromKeysValues = function(\n keys, values, opt_ignoreCase) {\n 'use strict';\n if (keys.length != values.length) {\n throw new Error('Mismatched lengths for keys/values');\n }\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n for (var i = 0; i < keys.length; i++) {\n queryData.add(keys[i], values[i]);\n }\n return queryData;\n};\n\n\n/**\n * @return {?number} The number of parameters.\n */\ngoog.Uri.QueryData.prototype.getCount = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_;\n};\n\n\n/**\n * Adds a key value pair.\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.add = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n key = this.getKeyName_(key);\n var values = this.keyMap_.get(key);\n if (!values) {\n this.keyMap_.set(key, (values = []));\n }\n values.push(value);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Removes all the params with the given key.\n * @param {string} key Name.\n * @return {boolean} Whether any parameter was removed.\n */\ngoog.Uri.QueryData.prototype.remove = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n\n key = this.getKeyName_(key);\n if (this.keyMap_.has(key)) {\n this.invalidateCache_();\n\n // Decrement parameter count.\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n return this.keyMap_.delete(key);\n }\n return false;\n};\n\n\n/**\n * Clears the parameters.\n */\ngoog.Uri.QueryData.prototype.clear = function() {\n 'use strict';\n this.invalidateCache_();\n this.keyMap_ = null;\n this.count_ = 0;\n};\n\n\n/**\n * @return {boolean} Whether we have any parameters.\n */\ngoog.Uri.QueryData.prototype.isEmpty = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_ == 0;\n};\n\n\n/**\n * Whether there is a parameter with the given name\n * @param {string} key The parameter name to check for.\n * @return {boolean} Whether there is a parameter with the given name.\n */\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n key = this.getKeyName_(key);\n return this.keyMap_.has(key);\n};\n\n\n/**\n * Whether there is a parameter with the given value.\n * @param {*} value The value to check for.\n * @return {boolean} Whether there is a parameter with the given value.\n */\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\n 'use strict';\n // NOTE(arv): This solution goes through all the params even if it was the\n // first param. We can get around this by not reusing code or by switching to\n // iterators.\n var vals = this.getValues();\n return goog.array.contains(vals, value);\n};\n\n\n/**\n * Runs a callback on every key-value pair in the map, including duplicate keys.\n * This won't maintain original order when duplicate keys are interspersed (like\n * getKeys() / getValues()).\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\n * @template SCOPE\n */\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(values, key) {\n 'use strict';\n values.forEach(function(value) {\n 'use strict';\n f.call(opt_scope, value, key, this);\n }, this);\n }, this);\n};\n\n\n/**\n * Returns all the keys of the parameters. If a key is used multiple times\n * it will be included multiple times in the returned array\n * @return {!Array<string>} All the keys of the parameters.\n */\ngoog.Uri.QueryData.prototype.getKeys = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n // We need to get the values to know how many keys to add.\n const vals = Array.from(this.keyMap_.values());\n const keys = Array.from(this.keyMap_.keys());\n const rv = [];\n for (let i = 0; i < keys.length; i++) {\n const val = vals[i];\n for (let j = 0; j < val.length; j++) {\n rv.push(keys[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Returns all the values of the parameters with the given name. If the query\n * data has no such key this will return an empty array. If no key is given\n * all values wil be returned.\n * @param {string=} opt_key The name of the parameter to get the values for.\n * @return {!Array<?>} All the values of the parameters with the given name.\n */\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n let rv = [];\n if (typeof opt_key === 'string') {\n if (this.containsKey(opt_key)) {\n rv = rv.concat(this.keyMap_.get(this.getKeyName_(opt_key)));\n }\n } else {\n // Return all values.\n const values = Array.from(this.keyMap_.values());\n for (let i = 0; i < values.length; i++) {\n rv = rv.concat(values[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Sets a key value pair and removes all other keys with the same value.\n *\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.set = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n // TODO(chrishenry): This could be better written as\n // this.remove(key), this.add(key, value), but that would reorder\n // the key (since the key is first removed and then added at the\n // end) and we would have to fix unit tests that depend on key\n // ordering.\n key = this.getKeyName_(key);\n if (this.containsKey(key)) {\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n }\n this.keyMap_.set(key, [value]);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Returns the first value associated with the key. If the query data has no\n * such key this will return undefined or the optional default.\n * @param {string} key The name of the parameter to get the value for.\n * @param {*=} opt_default The default value to return if the query data\n * has no such key.\n * @return {*} The first string value associated with the key, or opt_default\n * if there's no value.\n */\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\n 'use strict';\n if (!key) {\n return opt_default;\n }\n var values = this.getValues(key);\n return values.length > 0 ? String(values[0]) : opt_default;\n};\n\n\n/**\n * Sets the values for a key. If the key already exists, this will\n * override all of the existing values that correspond to the key.\n * @param {string} key The key to set values for.\n * @param {!Array<?>} values The values to set.\n */\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\n 'use strict';\n this.remove(key);\n\n if (values.length > 0) {\n this.invalidateCache_();\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\n }\n};\n\n\n/**\n * @return {string} Encoded query string.\n * @override\n */\ngoog.Uri.QueryData.prototype.toString = function() {\n 'use strict';\n if (this.encodedQuery_) {\n return this.encodedQuery_;\n }\n\n if (!this.keyMap_) {\n return '';\n }\n\n const sb = [];\n\n // In the past, we use this.getKeys() and this.getVals(), but that\n // generates a lot of allocations as compared to simply iterating\n // over the keys.\n const keys = Array.from(this.keyMap_.keys());\n for (var i = 0; i < keys.length; i++) {\n const key = keys[i];\n const encodedKey = goog.string.urlEncode(key);\n const val = this.getValues(key);\n for (var j = 0; j < val.length; j++) {\n var param = encodedKey;\n // Ensure that null and undefined are encoded into the url as\n // literal strings.\n if (val[j] !== '') {\n param += '=' + goog.string.urlEncode(val[j]);\n }\n sb.push(param);\n }\n }\n\n return this.encodedQuery_ = sb.join('&');\n};\n\n\n/**\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\n * any of the URI components).\n * @return {string} Decoded query string.\n */\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\n 'use strict';\n return goog.Uri.decodeOrEmpty_(this.toString());\n};\n\n\n/**\n * Invalidate the cache.\n * @private\n */\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\n 'use strict';\n this.encodedQuery_ = null;\n};\n\n\n/**\n * Removes all keys that are not in the provided list. (Modifies this object.)\n * @param {Array<string>} keys The desired keys.\n * @return {!goog.Uri.QueryData} a reference to this object.\n */\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n if (!goog.array.contains(keys, key)) {\n this.remove(key);\n }\n }, this);\n return this;\n};\n\n\n/**\n * Clone the query data instance.\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\n */\ngoog.Uri.QueryData.prototype.clone = function() {\n 'use strict';\n var rv = new goog.Uri.QueryData();\n rv.encodedQuery_ = this.encodedQuery_;\n if (this.keyMap_) {\n rv.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map(this.keyMap_));\n rv.count_ = this.count_;\n }\n return rv;\n};\n\n\n/**\n * Helper function to get the key name from a JavaScript object. Converts\n * the object to a string, and to lower case if necessary.\n * @private\n * @param {*} arg The object to get a key name from.\n * @return {string} valid key name which can be looked up in #keyMap_.\n */\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\n 'use strict';\n var keyName = String(arg);\n if (this.ignoreCase_) {\n keyName = keyName.toLowerCase();\n }\n return keyName;\n};\n\n\n/**\n * Ignore case in parameter names.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n */\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n var resetKeys = ignoreCase && !this.ignoreCase_;\n if (resetKeys) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n var lowerCase = key.toLowerCase();\n if (key != lowerCase) {\n this.remove(key);\n this.setValues(lowerCase, value);\n }\n }, this);\n }\n this.ignoreCase_ = ignoreCase;\n};\n\n\n/**\n * Extends a query data object with another query data or map like object. This\n * operates 'in-place', it does not create a new QueryData object.\n *\n * @param {...(?goog.Uri.QueryData|?goog.collections.maps.MapLike<?,\n * ?>|?Object)} var_args The object from which key value pairs will be\n * copied. Note: does not accept null.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters.\n */\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\n 'use strict';\n for (var i = 0; i < arguments.length; i++) {\n var data = arguments[i];\n goog.structs.forEach(data, function(value, key) {\n 'use strict';\n this.add(key, value);\n }, this);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The dispose method is used to clean up references and\n * resources.\n */\n\ngoog.module('goog.dispose');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls `dispose` on the argument if it supports it. If obj is not an\n * object with a dispose() method, this is a no-op.\n * @param {*} obj The object to dispose of.\n */\nfunction dispose(obj) {\n if (obj && typeof obj.dispose == 'function') {\n obj.dispose();\n }\n}\nexports = dispose;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\n * to support pluggable wire-format to improve wire efficiency and to enable\n * binary encoding. Such support will require an interface class, which\n * will be added later.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WireV8');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.json.NativeJsonProcessor');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.structs');\ngoog.requireType('goog.string.Parser');\n\n\n\n/**\n * The v8 codec class.\n *\n * @constructor\n * @struct\n */\ngoog.labs.net.webChannel.WireV8 = function() {\n 'use strict';\n /**\n * Parser for a response payload. The parser should return an array.\n * @private {!goog.string.Parser}\n */\n this.parser_ = new goog.json.NativeJsonProcessor();\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * Encodes a standalone message into the wire format.\n *\n * May throw exception if the message object contains any invalid elements.\n *\n * @param {!Object|!goog.collections.maps.MapLike} message The message data.\n * V8 only support JS objects (or Map).\n * @param {!Array<string>} buffer The text buffer to write the message to.\n * @param {string=} opt_prefix The prefix for each field of the object.\n */\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\n 'use strict';\n const prefix = opt_prefix || '';\n try {\n goog.structs.forEach(message, function(value, key) {\n 'use strict';\n let encodedValue = value;\n if (goog.isObject(value)) {\n encodedValue = goog.json.serialize(value);\n } // keep the fast-path for primitive types\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\n });\n } catch (ex) {\n // We send a map here because lots of the retry logic relies on map IDs,\n // so we have to send something (possibly redundant).\n buffer.push(\n prefix + 'type' +\n '=' + encodeURIComponent('_badmap'));\n throw ex;\n }\n};\n\n\n/**\n * Encodes all the buffered messages of the forward channel.\n *\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\n * V8 only support JS objects.\n * @param {number} count The number of messages to be encoded.\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\n * @return {string} the encoded messages\n */\nWireV8.prototype.encodeMessageQueue = function(\n messageQueue, count, badMapHandler) {\n 'use strict';\n let offset = -1;\n while (true) {\n const sb = ['count=' + count];\n // To save a bit of bandwidth, specify the base mapId and the rest as\n // offsets from it.\n if (offset == -1) {\n if (count > 0) {\n offset = messageQueue[0].mapId;\n sb.push('ofs=' + offset);\n } else {\n offset = 0;\n }\n } else {\n sb.push('ofs=' + offset);\n }\n let done = true;\n for (let i = 0; i < count; i++) {\n let mapId = messageQueue[i].mapId;\n const map = messageQueue[i].map;\n mapId -= offset;\n if (mapId < 0) {\n // redo the encoding in case of retry/reordering, plus extra space\n offset = Math.max(0, messageQueue[i].mapId - 100);\n done = false;\n continue;\n }\n try {\n this.encodeMessage(map, sb, 'req' + mapId + '_');\n } catch (ex) {\n if (badMapHandler) {\n badMapHandler(map);\n }\n }\n }\n if (done) {\n return sb.join('&');\n }\n }\n};\n\n\n/**\n * Decodes a standalone message received from the wire. May throw exception\n * if text is ill-formatted.\n *\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\n * and eval() is disallowed in Chrome apps too.\n *\n * Invalid JS literals include null array elements, quotas etc.\n *\n * @param {string} messageText The string content as received from the wire.\n * @return {*} The decoded message object.\n */\nWireV8.prototype.decodeMessage = function(messageText) {\n 'use strict';\n const response = this.parser_.parse(messageText);\n goog.asserts.assert(Array.isArray(response)); // throw exception\n return response;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for string manipulation.\n */\n\n\n/**\n * Namespace for string utilities\n */\ngoog.provide('goog.string');\ngoog.provide('goog.string.Unicode');\n\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\n * with detection of double-escaping as this letter is frequently used.\n */\ngoog.string.DETECT_DOUBLE_ESCAPING =\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\n\n\n/**\n * @define {boolean} Whether to force non-dom html unescaping.\n */\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\n\n\n/**\n * Common Unicode string characters.\n * @enum {string}\n */\ngoog.string.Unicode = {\n NBSP: '\\xa0'\n};\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n */\ngoog.string.startsWith = goog.string.internal.startsWith;\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n */\ngoog.string.endsWith = goog.string.internal.endsWith;\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveStartsWith =\n goog.string.internal.caseInsensitiveStartsWith;\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveEndsWith =\n goog.string.internal.caseInsensitiveEndsWith;\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n */\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\n\n\n/**\n * Does simple python-style string substitution.\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\n * @param {string} str The string containing the pattern.\n * @param {...*} var_args The items to substitute into the pattern.\n * @return {string} A copy of `str` in which each occurrence of\n * {@code %s} has been replaced an argument from `var_args`.\n */\ngoog.string.subs = function(str, var_args) {\n 'use strict';\n const splitParts = str.split('%s');\n let returnString = '';\n\n const subsArguments = Array.prototype.slice.call(arguments, 1);\n while (subsArguments.length &&\n // Replace up to the last split part. We are inserting in the\n // positions between split parts.\n splitParts.length > 1) {\n returnString += splitParts.shift() + subsArguments.shift();\n }\n\n return returnString + splitParts.join('%s'); // Join unused '%s'\n};\n\n\n/**\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\n * and tabs) to a single space, and strips leading and trailing whitespace.\n * @param {string} str Input string.\n * @return {string} A copy of `str` with collapsed whitespace.\n */\ngoog.string.collapseWhitespace = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n */\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is empty.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty.\n */\ngoog.string.isEmptyString = function(str) {\n 'use strict';\n return str.length == 0;\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n *\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\n * instead.\n */\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\n 'use strict';\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\n};\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n *\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\n\n\n/**\n * Checks if a string is all breaking whitespace.\n * @param {string} str The string to check.\n * @return {boolean} Whether the string is all breaking whitespace.\n */\ngoog.string.isBreakingWhitespace = function(str) {\n 'use strict';\n return !/[^\\t\\n\\r ]/.test(str);\n};\n\n\n/**\n * Checks if a string contains all letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` consists entirely of letters.\n */\ngoog.string.isAlpha = function(str) {\n 'use strict';\n return !/[^a-zA-Z]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers.\n * @param {*} str string to check. If not a string, it will be\n * casted to one.\n * @return {boolean} True if `str` is numeric.\n */\ngoog.string.isNumeric = function(str) {\n 'use strict';\n return !/[^0-9]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers or letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` is alphanumeric.\n */\ngoog.string.isAlphaNumeric = function(str) {\n 'use strict';\n return !/[^a-zA-Z0-9]/.test(str);\n};\n\n\n/**\n * Checks if a character is a space character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a space.\n */\ngoog.string.isSpace = function(ch) {\n 'use strict';\n return ch == ' ';\n};\n\n\n/**\n * Checks if a character is a valid unicode character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a valid unicode character.\n */\ngoog.string.isUnicodeChar = function(ch) {\n 'use strict';\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\n ch >= '\\u0080' && ch <= '\\uFFFD';\n};\n\n\n/**\n * Takes a string and replaces newlines with a space. Multiple lines are\n * replaced with a single space.\n * @param {string} str The string from which to strip newlines.\n * @return {string} A copy of `str` stripped of newlines.\n */\ngoog.string.stripNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\n};\n\n\n/**\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\n * @param {string} str The string to in which to canonicalize newlines.\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\n */\ngoog.string.canonicalizeNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\n};\n\n\n/**\n * Normalizes whitespace in a string, replacing all whitespace chars with\n * a space.\n * @param {string} str The string in which to normalize whitespace.\n * @return {string} A copy of `str` with all whitespace normalized.\n */\ngoog.string.normalizeWhitespace = function(str) {\n 'use strict';\n return str.replace(/\\xa0|\\s/g, ' ');\n};\n\n\n/**\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\n * with a single space. Replaces non-breaking space with a space.\n * @param {string} str The string in which to normalize spaces.\n * @return {string} A copy of `str` with all consecutive spaces and tabs\n * replaced with a single space.\n */\ngoog.string.normalizeSpaces = function(str) {\n 'use strict';\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\n};\n\n\n/**\n * Removes the breaking spaces from the left and right of the string and\n * collapses the sequences of breaking spaces in the middle into single spaces.\n * The original and the result strings render the same way in HTML.\n * @param {string} str A string in which to collapse spaces.\n * @return {string} Copy of the string with normalized breaking spaces.\n */\ngoog.string.collapseBreakingSpaces = function(str) {\n 'use strict';\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trim = goog.string.internal.trim;\n\n\n/**\n * Trims whitespaces at the left end of a string.\n * @param {string} str The string to left trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimLeft = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/^[\\s\\xa0]+/, '');\n};\n\n\n/**\n * Trims whitespaces at the right end of a string.\n * @param {string} str The string to right trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimRight = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+$/, '');\n};\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n */\ngoog.string.caseInsensitiveCompare =\n goog.string.internal.caseInsensitiveCompare;\n\n\n/**\n * Compares two strings interpreting their numeric substrings as numbers.\n *\n * @param {string} str1 First string.\n * @param {string} str2 Second string.\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\n * non-negative integers, non-numeric characters and optionally fractional\n * numbers starting with a decimal point.\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\n * str1 > str2.\n * @private\n */\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\n 'use strict';\n if (str1 == str2) {\n return 0;\n }\n if (!str1) {\n return -1;\n }\n if (!str2) {\n return 1;\n }\n\n // Using match to split the entire string ahead of time turns out to be faster\n // for most inputs than using RegExp.exec or iterating over each character.\n const tokens1 = str1.toLowerCase().match(tokenizerRegExp);\n const tokens2 = str2.toLowerCase().match(tokenizerRegExp);\n\n const count = Math.min(tokens1.length, tokens2.length);\n\n for (let i = 0; i < count; i++) {\n const a = tokens1[i];\n const b = tokens2[i];\n\n // Compare pairs of tokens, returning if one token sorts before the other.\n if (a != b) {\n // Only if both tokens are integers is a special comparison required.\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\n const num1 = parseInt(a, 10);\n if (!isNaN(num1)) {\n const num2 = parseInt(b, 10);\n if (!isNaN(num2) && num1 - num2) {\n return num1 - num2;\n }\n }\n return a < b ? -1 : 1;\n }\n }\n\n // If one string is a substring of the other, the shorter string sorts first.\n if (tokens1.length != tokens2.length) {\n return tokens1.length - tokens2.length;\n }\n\n // The two strings must be equivalent except for case (perfect equality is\n // tested at the head of the function.) Revert to default ASCII string\n // comparison to stabilize the sort.\n return str1 < str2 ? -1 : 1;\n};\n\n\n/**\n * String comparison function that handles non-negative integer numbers in a\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\n * is mostly case-insensitive, though strings that are identical except for case\n * are sorted with the upper-case strings before lower-case.\n *\n * This comparison function is up to 50x slower than either the default or the\n * case-insensitive compare. It should not be used in time-critical code, but\n * should be fast enough to sort several hundred short strings (like filenames)\n * with a reasonable delay.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.intAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\n};\n\n\n/**\n * String comparison function that handles non-negative integer and fractional\n * numbers in a way humans might expect. Using this function, the string\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\n * dots.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.floatAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\n};\n\n\n/**\n * Alias for {@link goog.string.floatAwareCompare}.\n *\n * @param {string} str1\n * @param {string} str2\n * @return {number}\n */\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\n\n\n/**\n * URL-encodes a string\n * @param {*} str The string to url-encode.\n * @return {string} An encoded copy of `str` that is safe for urls.\n * Note that '#', ':', and other characters used to delimit portions\n * of URLs *will* be encoded.\n */\ngoog.string.urlEncode = function(str) {\n 'use strict';\n return encodeURIComponent(String(str));\n};\n\n\n/**\n * URL-decodes the string. We need to specially handle '+'s because\n * the javascript library doesn't convert them to spaces.\n * @param {string} str The string to url decode.\n * @return {string} The decoded `str`.\n */\ngoog.string.urlDecode = function(str) {\n 'use strict';\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n */\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n *\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\n * be valid, but it has been decided to escape it for consistency with other\n * implementations.\n *\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\n * lowercase letter \"e\".\n *\n * NOTE(user):\n * HtmlEscape is often called during the generation of large blocks of HTML.\n * Using statics for the regular expressions and strings is an optimization\n * that can more than half the amount of time IE spends in this function for\n * large apps, since strings and regexes both contribute to GC allocations.\n *\n * Testing for the presence of a character before escaping increases the number\n * of function calls, but actually provides a speed increase for the average\n * case -- since the average case often doesn't require the escaping of all 4\n * characters and indexOf() is much cheaper than replace().\n * The worst case does suffer slightly from the additional calls, therefore the\n * opt_isLikelyToContainHtmlChars option has been included for situations\n * where all 4 HTML entities are very likely to be present and need escaping.\n *\n * Some benchmarks (times tended to fluctuate +-0.05ms):\n * FireFox IE6\n * (no chars / average (mix of cases) / all 4 chars)\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\n *\n * An additional advantage of checking if replace actually needs to be called\n * is a reduction in the number of object allocations, so as the size of the\n * application grows the difference between the various methods would increase.\n *\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\n * if the character needs replacing - use this option if you expect each of\n * the characters to appear often. Leave false if you expect few html\n * characters to occur in your strings, such as if you are escaping HTML.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\n str = str.replace(goog.string.E_RE_, '&#101;');\n }\n return str;\n};\n\n\n/**\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.E_RE_ = /e/g;\n\n\n/**\n * Unescapes an HTML string.\n *\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntities = function(str) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n // We are careful not to use a DOM if we do not have one or we explicitly\n // requested non-DOM html unescaping.\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\n 'document' in goog.global) {\n return goog.string.unescapeEntitiesUsingDom_(str);\n } else {\n // Fall back on pure XML entities\n return goog.string.unescapePureXmlEntities_(str);\n }\n }\n return str;\n};\n\n\n/**\n * Unescapes a HTML string using the provided document.\n *\n * @param {string} str The string to unescape.\n * @param {!Document} document A document to use in escaping the string.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n return goog.string.unescapeEntitiesUsingDom_(str, document);\n }\n return str;\n};\n\n\n/**\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\n * entities. This function is XSS-safe and whitespace-preserving.\n * @private\n * @param {string} str The string to unescape.\n * @param {Document=} opt_document An optional document to use for creating\n * elements. If this is not specified then the default window.document\n * will be used.\n * @return {string} The unescaped `str` string.\n */\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\n 'use strict';\n /** @type {!Object<string, string>} */\n const seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"'};\n /** @type {!Element} */\n let div;\n if (opt_document) {\n div = opt_document.createElement('div');\n } else {\n div = goog.global.document.createElement('div');\n }\n // Match as many valid entity characters as possible. If the actual entity\n // happens to be shorter, it will still work as innerHTML will return the\n // trailing characters unchanged. Since the entity characters do not include\n // open angle bracket, there is no chance of XSS from the innerHTML use.\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\n 'use strict';\n // Check for cached entity.\n let value = seen[s];\n if (value) {\n return value;\n }\n // Check for numeric entity.\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers.\n const n = Number('0' + entity.substr(1));\n if (!isNaN(n)) {\n value = String.fromCharCode(n);\n }\n }\n // Fall back to innerHTML otherwise.\n if (!value) {\n // Append a non-entity character to avoid a bug in Webkit that parses\n // an invalid entity at the end of innerHTML text as the empty string.\n goog.dom.safe.setInnerHtml(\n div,\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from('Single HTML entity.'), s + ' '));\n // Then remove the trailing character from the result.\n value = div.firstChild.nodeValue.slice(0, -1);\n }\n // Cache and return.\n return seen[s] = value;\n });\n};\n\n\n/**\n * Unescapes XML entities.\n * @private\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapePureXmlEntities_ = function(str) {\n 'use strict';\n return str.replace(/&([^;]+);/g, function(s, entity) {\n 'use strict';\n switch (entity) {\n case 'amp':\n return '&';\n case 'lt':\n return '<';\n case 'gt':\n return '>';\n case 'quot':\n return '\"';\n default:\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex.\n const n = Number('0' + entity.substr(1));\n if (!isNaN(n)) {\n return String.fromCharCode(n);\n }\n }\n // For invalid entities we just return the entity\n return s;\n }\n });\n};\n\n\n/**\n * Regular expression that matches an HTML entity.\n * See also HTML5: Tokenization / Tokenizing character references.\n * @private\n * @type {!RegExp}\n */\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml);\n};\n\n\n/**\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\n * with non-breaking space Unicode characters.\n * @param {string} str The string in which to preserve whitespace.\n * @return {string} A copy of `str` with preserved whitespace.\n */\ngoog.string.preserveSpaces = function(str) {\n 'use strict';\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\n};\n\n\n/**\n * Strip quote characters around a string. The second argument is a string of\n * characters to treat as quotes. This can be a single character or a string of\n * multiple character and in that case each of those are treated as possible\n * quote characters. For example:\n *\n * <pre>\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\n * </pre>\n *\n * @param {string} str The string to strip.\n * @param {string} quoteChars The quote characters to strip.\n * @return {string} A copy of `str` without the quotes.\n */\ngoog.string.stripQuotes = function(str, quoteChars) {\n 'use strict';\n const length = quoteChars.length;\n for (let i = 0; i < length; i++) {\n const quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\n return str.substring(1, str.length - 1);\n }\n }\n return str;\n};\n\n\n/**\n * Truncates a string to a certain length and adds '...' if necessary. The\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\n * 'Hello World!' produces 'Hello W...'.\n * @param {string} str The string to truncate.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cut off in the middle.\n * @return {string} The truncated `str` string.\n */\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (str.length > chars) {\n str = str.substring(0, chars - 3) + '...';\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Truncate a string in the middle, adding \"...\" if necessary,\n * and favoring the beginning of the string.\n * @param {string} str The string to truncate the middle of.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cutoff in the middle.\n * @param {number=} opt_trailingChars Optional number of trailing characters to\n * leave at the end of the string, instead of truncating as close to the\n * middle as possible.\n * @return {string} A truncated copy of `str`.\n */\ngoog.string.truncateMiddle = function(\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (opt_trailingChars && str.length > chars) {\n if (opt_trailingChars > chars) {\n opt_trailingChars = chars;\n }\n const endPoint = str.length - opt_trailingChars;\n const startPoint = chars - opt_trailingChars;\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\n } else if (str.length > chars) {\n // Favor the beginning of the string:\n let half = Math.floor(chars / 2);\n const endPos = str.length - half;\n half += chars % 2;\n str = str.substring(0, half) + '...' + str.substring(endPos);\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Special chars that need to be escaped for goog.string.quote.\n * @private {!Object<string, string>}\n */\ngoog.string.specialEscapeChars_ = {\n '\\0': '\\\\0',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n // To support the use case of embedding quoted strings inside of script\n // tags, we have to make sure HTML comments and opening/closing script tags do\n // not appear in the resulting string. The specific strings that must be\n // escaped are documented at:\n // https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements\n '<': '\\\\u003C' // NOTE: JSON.parse crashes on '\\\\x3c'.\n};\n\n\n/**\n * Character mappings used internally for goog.string.escapeChar.\n * @private {!Object<string, string>}\n */\ngoog.string.jsEscapeCache_ = {\n '\\'': '\\\\\\''\n};\n\n\n/**\n * Encloses a string in double quotes and escapes characters so that the\n * string is a valid JS string. The resulting string is safe to embed in\n * `<script>` tags as \"<\" is escaped.\n * @param {string} s The string to quote.\n * @return {string} A copy of `s` surrounded by double quotes.\n */\ngoog.string.quote = function(s) {\n 'use strict';\n s = String(s);\n const sb = ['\"'];\n for (let i = 0; i < s.length; i++) {\n const ch = s.charAt(i);\n const cc = ch.charCodeAt(0);\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\n }\n sb.push('\"');\n return sb.join('');\n};\n\n\n/**\n * Takes a string and returns the escaped string for that input string.\n * @param {string} str The string to escape.\n * @return {string} An escaped string representing `str`.\n */\ngoog.string.escapeString = function(str) {\n 'use strict';\n const sb = [];\n for (let i = 0; i < str.length; i++) {\n sb[i] = goog.string.escapeChar(str.charAt(i));\n }\n return sb.join('');\n};\n\n\n/**\n * Takes a character and returns the escaped string for that character. For\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\n * @param {string} c The character to escape.\n * @return {string} An escaped string representing `c`.\n */\ngoog.string.escapeChar = function(c) {\n 'use strict';\n if (c in goog.string.jsEscapeCache_) {\n return goog.string.jsEscapeCache_[c];\n }\n\n if (c in goog.string.specialEscapeChars_) {\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\n }\n\n let rv = c;\n const cc = c.charCodeAt(0);\n if (cc > 31 && cc < 127) {\n rv = c;\n } else {\n // tab is 9 but handled above\n if (cc < 256) {\n rv = '\\\\x';\n if (cc < 16 || cc > 256) {\n rv += '0';\n }\n } else {\n rv = '\\\\u';\n if (cc < 4096) { // \\u1000\n rv += '0';\n }\n }\n rv += cc.toString(16).toUpperCase();\n }\n\n return goog.string.jsEscapeCache_[c] = rv;\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.contains = goog.string.internal.contains;\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.caseInsensitiveContains =\n goog.string.internal.caseInsensitiveContains;\n\n\n/**\n * Returns the non-overlapping occurrences of ss in s.\n * If either s or ss evalutes to false, then returns zero.\n * @param {string} s The string to look in.\n * @param {string} ss The string to look for.\n * @return {number} Number of occurrences of ss in s.\n */\ngoog.string.countOf = function(s, ss) {\n 'use strict';\n return s && ss ? s.split(ss).length - 1 : 0;\n};\n\n\n/**\n * Removes a substring of a specified length at a specific\n * index in a string.\n * @param {string} s The base string from which to remove.\n * @param {number} index The index at which to remove the substring.\n * @param {number} stringLength The length of the substring to remove.\n * @return {string} A copy of `s` with the substring removed or the full\n * string if nothing is removed or the input is invalid.\n */\ngoog.string.removeAt = function(s, index, stringLength) {\n 'use strict';\n let resultStr = s;\n // If the index is greater or equal to 0 then remove substring\n if (index >= 0 && index < s.length && stringLength > 0) {\n resultStr = s.substr(0, index) +\n s.substr(index + stringLength, s.length - index - stringLength);\n }\n return resultStr;\n};\n\n\n/**\n * Removes the first occurrence of a substring from a string.\n * @param {string} str The base string from which to remove.\n * @param {string} substr The string to remove.\n * @return {string} A copy of `str` with `substr` removed or the\n * full string if nothing is removed.\n */\ngoog.string.remove = function(str, substr) {\n 'use strict';\n return str.replace(substr, '');\n};\n\n\n/**\n * Removes all occurrences of a substring from a string.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to remove.\n * @return {string} A copy of `s` with `ss` removed or the full\n * string if nothing is removed.\n */\ngoog.string.removeAll = function(s, ss) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, '');\n};\n\n\n/**\n * Replaces all occurrences of a substring of a string with a new substring.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to replace.\n * @param {string} replacement The replacement string.\n * @return {string} A copy of `s` with `ss` replaced by\n * `replacement` or the original string if nothing is replaced.\n */\ngoog.string.replaceAll = function(s, ss, replacement) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\n};\n\n\n/**\n * Escapes characters in the string that are not safe to use in a RegExp.\n * @param {*} s The string to escape. If not a string, it will be casted\n * to one.\n * @return {string} A RegExp safe, escaped copy of `s`.\n */\ngoog.string.regExpEscape = function(s) {\n 'use strict';\n return String(s)\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\n .replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * Repeats a string n times.\n * @param {string} string The string to repeat.\n * @param {number} length The number of times to repeat.\n * @return {string} A string containing `length` repetitions of\n * `string`.\n */\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\n 'use strict';\n // The native method is over 100 times faster than the alternative.\n return string.repeat(length);\n} : function(string, length) {\n 'use strict';\n return new Array(length + 1).join(string);\n};\n\n\n/**\n * Pads number to given length and optionally rounds it to a given precision.\n * For example:\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\n * padNumber(1.25, 2) -> '01.25'\n * padNumber(1.25, 2, 1) -> '01.3'\n * padNumber(1.25, 0) -> '1.25'</pre>\n *\n * @param {number} num The number to pad.\n * @param {number} length The desired length.\n * @param {number=} opt_precision The desired precision.\n * @return {string} `num` as a string with the given options.\n */\ngoog.string.padNumber = function(num, length, opt_precision) {\n 'use strict';\n if (!Number.isFinite(num)) return String(num);\n let s =\n (opt_precision !== undefined) ? num.toFixed(opt_precision) : String(num);\n let index = s.indexOf('.');\n if (index === -1) {\n index = s.length;\n }\n const sign = s[0] === '-' ? '-' : '';\n if (sign) {\n s = s.substring(1);\n }\n return sign + goog.string.repeat('0', Math.max(0, length - index)) + s;\n};\n\n\n/**\n * Returns a string representation of the given object, with\n * null and undefined being returned as the empty string.\n *\n * @param {*} obj The object to convert.\n * @return {string} A string representation of the `obj`.\n */\ngoog.string.makeSafe = function(obj) {\n 'use strict';\n return obj == null ? '' : String(obj);\n};\n\n/**\n * Returns a string with at least 64-bits of randomness.\n *\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\n * random and current timestamp, and then encodes the string in base-36 to\n * make it shorter.\n *\n * @return {string} A random string, e.g. sn1s7vb4gcic.\n */\ngoog.string.getRandomString = function() {\n 'use strict';\n const x = 2147483648;\n return Math.floor(Math.random() * x).toString(36) +\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n */\ngoog.string.compareVersions = goog.string.internal.compareVersions;\n\n\n/**\n * String hash function similar to java.lang.String.hashCode().\n * The hash code for a string is computed as\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n * where s[i] is the ith character of the string and n is the length of\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\n * (exclusive).\n * @param {string} str A string.\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\n * (exclusive). The empty string returns 0.\n */\ngoog.string.hashCode = function(str) {\n 'use strict';\n let result = 0;\n for (let i = 0; i < str.length; ++i) {\n // Normalize to 4 byte range, 0 ... 2^32.\n result = (31 * result + str.charCodeAt(i)) >>> 0;\n }\n return result;\n};\n\n\n/**\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\n * @type {number}\n * @private\n */\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\n\n\n/**\n * Generates and returns a string which is unique in the current document.\n * This is useful, for example, to create unique IDs for DOM elements.\n * @return {string} A unique id.\n */\ngoog.string.createUniqueString = function() {\n 'use strict';\n return 'goog_' + goog.string.uniqueStringCounter_++;\n};\n\n\n/**\n * Converts the supplied string to a number, which may be Infinity or NaN.\n * This function strips whitespace: (toNumber(' 123') === 123)\n * This function accepts scientific notation: (toNumber('1e1') === 10)\n *\n * This is better than JavaScript's built-in conversions because, sadly:\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\n *\n * @param {string} str The string to convert.\n * @return {number} The number the supplied string represents, or NaN.\n */\ngoog.string.toNumber = function(str) {\n 'use strict';\n const num = Number(str);\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\n return NaN;\n }\n return num;\n};\n\n\n/**\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is lower camel case.\n */\ngoog.string.isLowerCamelCase = function(str) {\n 'use strict';\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\n};\n\n\n/**\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is upper camel case.\n */\ngoog.string.isUpperCamelCase = function(str) {\n 'use strict';\n return /^([A-Z][a-z]*)+$/.test(str);\n};\n\n\n/**\n * Converts a string from selector-case to camelCase (e.g. from\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\n * @param {string} str The string in selector-case form.\n * @return {string} The string in camelCase form.\n */\ngoog.string.toCamelCase = function(str) {\n 'use strict';\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\n 'use strict';\n return match.toUpperCase();\n });\n};\n\n\n/**\n * Converts a string from camelCase to selector-case (e.g. from\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\n * style and dataset properties to equivalent CSS selectors and HTML keys.\n * @param {string} str The string in camelCase form.\n * @return {string} The string in selector-case form.\n */\ngoog.string.toSelectorCase = function(str) {\n 'use strict';\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\n};\n\n\n/**\n * Converts a string into TitleCase. First character of the string is always\n * capitalized in addition to the first letter of every subsequent word.\n * Words are delimited by one or more whitespaces by default. Custom delimiters\n * can optionally be specified to replace the default, which doesn't preserve\n * whitespace delimiters and instead must be explicitly included if needed.\n *\n * Default delimiter => \" \":\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three') => 'One Two Three'\n * goog.string.toTitleCase(' one two ') => ' One Two '\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\n *\n * Custom delimiter => \"_-.\":\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\n *\n * @param {string} str String value in camelCase form.\n * @param {string=} opt_delimiters Custom delimiter character set used to\n * distinguish words in the string value. Each character represents a\n * single delimiter. When provided, default whitespace delimiter is\n * overridden and must be explicitly included if needed.\n * @return {string} String value in TitleCase form.\n */\ngoog.string.toTitleCase = function(str, opt_delimiters) {\n 'use strict';\n let delimiters = (typeof opt_delimiters === 'string') ?\n goog.string.regExpEscape(opt_delimiters) :\n '\\\\s';\n\n // For IE8, we need to prevent using an empty character set. Otherwise,\n // incorrect matching will occur.\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\n\n const regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\n return str.replace(regexp, function(all, p1, p2) {\n 'use strict';\n return p1 + p2.toUpperCase();\n });\n};\n\n\n/**\n * Capitalizes a string, i.e. converts the first letter to uppercase\n * and all other letters to lowercase, e.g.:\n *\n * goog.string.capitalize('one') => 'One'\n * goog.string.capitalize('ONE') => 'One'\n * goog.string.capitalize('one two') => 'One two'\n *\n * Note that this function does not trim initial whitespace.\n *\n * @param {string} str String value to capitalize.\n * @return {string} String value with first letter in uppercase.\n */\ngoog.string.capitalize = function(str) {\n 'use strict';\n return String(str.charAt(0)).toUpperCase() +\n String(str.substr(1)).toLowerCase();\n};\n\n\n/**\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\n *\n * To parse a particular radix, please use parseInt(string, radix) directly. See\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\n *\n * This is a wrapper for the built-in parseInt function that will only parse\n * numbers as base 10 or base 16. Some JS implementations assume strings\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\n *\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\n *\n * @param {string|number|null|undefined} value The value to be parsed.\n * @return {number} The number, parsed. If the string failed to parse, this\n * will be NaN.\n */\ngoog.string.parseInt = function(value) {\n 'use strict';\n // Force finite numbers to strings.\n if (isFinite(value)) {\n value = String(value);\n }\n\n if (typeof value === 'string') {\n // If the string starts with '0x' or '-0x', parse as hex.\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\n }\n\n return NaN;\n};\n\n\n/**\n * Splits a string on a separator a limited number of times.\n *\n * This implementation is more similar to Python or Java, where the limit\n * parameter specifies the maximum number of splits rather than truncating\n * the number of results.\n *\n * See http://docs.python.org/2/library/stdtypes.html#str.split\n * See JavaDoc: http://goo.gl/F2AsY\n * See Mozilla reference: http://goo.gl/dZdZs\n *\n * @param {string} str String to split.\n * @param {string} separator The separator.\n * @param {number} limit The limit to the number of splits. The resulting array\n * will have a maximum length of limit+1. Negative numbers are the same\n * as zero.\n * @return {!Array<string>} The string, split.\n */\ngoog.string.splitLimit = function(str, separator, limit) {\n 'use strict';\n const parts = str.split(separator);\n const returnVal = [];\n\n // Only continue doing this while we haven't hit the limit and we have\n // parts left.\n while (limit > 0 && parts.length) {\n returnVal.push(parts.shift());\n limit--;\n }\n\n // If there are remaining parts, append them to the end.\n if (parts.length) {\n returnVal.push(parts.join(separator));\n }\n\n return returnVal;\n};\n\n\n/**\n * Finds the characters to the right of the last instance of any separator\n *\n * This function is similar to goog.string.path.baseName, except it can take a\n * list of characters to split the string on. It will return the rightmost\n * grouping of characters to the right of any separator as a left-to-right\n * oriented string.\n *\n * @see goog.string.path.baseName\n * @param {string} str The string\n * @param {string|!Array<string>} separators A list of separator characters\n * @return {string} The last part of the string with respect to the separators\n */\ngoog.string.lastComponent = function(str, separators) {\n 'use strict';\n if (!separators) {\n return str;\n } else if (typeof separators == 'string') {\n separators = [separators];\n }\n\n let lastSeparatorIndex = -1;\n for (let i = 0; i < separators.length; i++) {\n if (separators[i] == '') {\n continue;\n }\n const currentSeparatorIndex = str.lastIndexOf(separators[i]);\n if (currentSeparatorIndex > lastSeparatorIndex) {\n lastSeparatorIndex = currentSeparatorIndex;\n }\n }\n if (lastSeparatorIndex == -1) {\n return str;\n }\n return str.slice(lastSeparatorIndex + 1);\n};\n\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n * @param {string} a\n * @param {string} b\n * @return {number} The edit distance between the two strings.\n */\ngoog.string.editDistance = function(a, b) {\n 'use strict';\n const v0 = [];\n const v1 = [];\n\n if (a == b) {\n return 0;\n }\n\n if (!a.length || !b.length) {\n return Math.max(a.length, b.length);\n }\n\n for (let i = 0; i < b.length + 1; i++) {\n v0[i] = i;\n }\n\n for (let i = 0; i < a.length; i++) {\n v1[0] = i + 1;\n\n for (let j = 0; j < b.length; j++) {\n const cost = Number(a[i] != b[j]);\n // Cost for the substring is the minimum of adding one character, removing\n // one character, or a swap.\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\n }\n\n for (let j = 0; j < v0.length; j++) {\n v0[j] = v1[j];\n }\n }\n\n return v1[b.length];\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A pool of forward channel requests to enable real-time\n * messaging from the client to server.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\n\ngoog.module.declareLegacyNamespace();\n\nconst ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\nconst Wire = goog.require('goog.labs.net.webChannel.Wire');\nconst array = goog.require('goog.array');\nconst googString = goog.require('goog.string');\n\n\n/**\n * This class represents the state of all forward channel requests.\n *\n * @param {number=} opt_maxPoolSize The maximum pool size.\n *\n * @struct @constructor @final\n */\nconst ForwardChannelRequestPool = function(opt_maxPoolSize) {\n /**\n * The max pool size as configured.\n *\n * @private {number}\n */\n this.maxPoolSizeConfigured_ =\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\n\n /**\n * The current size limit of the request pool. This limit is meant to be\n * read-only after the channel is fully opened.\n *\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\n * configurable.\n *\n * @private {number}\n */\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\n this.maxPoolSizeConfigured_ :\n 1;\n\n /**\n * The container for all the pending request objects.\n *\n * @private {?Set<?ChannelRequest>}\n */\n this.requestPool_ = null;\n\n if (this.maxSize_ > 1) {\n this.requestPool_ = new Set();\n }\n\n /**\n * The single request object when the pool size is limited to one.\n *\n * @private {?ChannelRequest}\n */\n this.request_ = null;\n\n /**\n * Saved pending messages when the pool is cancelled.\n *\n * @private {!Array<Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n};\n\n\n/**\n * The default size limit of the request pool.\n *\n * @private {number}\n */\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\n\n\n/**\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\n * as a fallback and will always return false for other browsers where\n * PerformanceNavigationTiming is not available.\n * @private\n */\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\n if (goog.global.PerformanceNavigationTiming) {\n const entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\n goog.global.performance.getEntriesByType('navigation'));\n return entrys.length > 0 &&\n (entrys[0].nextHopProtocol == 'hq' ||\n entrys[0].nextHopProtocol == 'h2');\n }\n return !!(\n goog.global.chrome && goog.global.chrome.loadTimes &&\n goog.global.chrome.loadTimes() &&\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\n};\n\n\n/**\n * Once we know the client protocol (from the handshake), check if we need\n * enable the request pool accordingly. This is more robust than using\n * browser-internal APIs (specific to Chrome).\n *\n * @param {string} clientProtocol The client protocol\n */\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\n clientProtocol) {\n if (this.requestPool_) {\n return;\n }\n\n if (googString.contains(clientProtocol, 'spdy') ||\n googString.contains(clientProtocol, 'quic') ||\n googString.contains(clientProtocol, 'h2')) {\n this.maxSize_ = this.maxPoolSizeConfigured_;\n this.requestPool_ = new Set();\n if (this.request_) {\n this.addRequest(this.request_);\n this.request_ = null;\n }\n }\n};\n\n\n/**\n * @return {boolean} True if the pool is full.\n */\nForwardChannelRequestPool.prototype.isFull = function() {\n if (this.request_) {\n return true;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size >= this.maxSize_;\n }\n\n return false;\n};\n\n\n/**\n * @return {number} The current size limit.\n */\nForwardChannelRequestPool.prototype.getMaxSize = function() {\n return this.maxSize_;\n};\n\n\n/**\n * @return {number} The number of pending requests in the pool.\n */\nForwardChannelRequestPool.prototype.getRequestCount = function() {\n if (this.request_) {\n return 1;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size;\n }\n\n return 0;\n};\n\n\n/**\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} True if the request is a included inside the pool.\n */\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\n if (this.request_) {\n return this.request_ == req;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.has(req);\n }\n\n return false;\n};\n\n\n/**\n * Adds a new request to the pool.\n *\n * @param {!ChannelRequest} req The new channel request.\n */\nForwardChannelRequestPool.prototype.addRequest = function(req) {\n if (this.requestPool_) {\n this.requestPool_.add(req);\n } else {\n this.request_ = req;\n }\n};\n\n\n/**\n * Removes the given request from the pool.\n *\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} Whether the request has been removed from the pool.\n */\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\n if (this.request_ && this.request_ == req) {\n this.request_ = null;\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.has(req)) {\n this.requestPool_.delete(req);\n return true;\n }\n\n return false;\n};\n\n\n/**\n * Clears the pool and cancel all the pending requests.\n */\nForwardChannelRequestPool.prototype.cancel = function() {\n // save any pending messages\n this.pendingMessages_ = this.getPendingMessages();\n\n if (this.request_) {\n this.request_.cancel();\n this.request_ = null;\n return;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n }\n this.requestPool_.clear();\n }\n};\n\n\n/**\n * @return {boolean} Whether there are any pending requests.\n */\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\n return (this.request_ != null) ||\n (this.requestPool_ != null && this.requestPool_.size !== 0);\n};\n\n\n/**\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\n * as a new array.\n */\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\n if (this.request_ != null) {\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\n }\n\n if (this.requestPool_ != null && this.requestPool_.size !== 0) {\n let result = this.pendingMessages_;\n for (const val of this.requestPool_.values()) {\n result = result.concat(val.getPendingMessages());\n }\n return result;\n }\n\n return array.clone(this.pendingMessages_);\n};\n\n\n/**\n * Records pending messages, e.g. when a request receives a failed response.\n *\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\n */\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\n};\n\n\n/**\n * Clears any recorded pending messages.\n */\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\n this.pendingMessages_.length = 0;\n};\n\n\n/**\n * Cancels all pending requests and force the completion of channel requests.\n *\n * Need go through the standard onRequestComplete logic to expose the max-retry\n * failure in the standard way.\n *\n * @param {function(!ChannelRequest)} onComplete The completion callback.\n * @return {boolean} true if any request has been forced to complete.\n */\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\n if (this.request_ != null) {\n this.request_.cancel();\n onComplete(this.request_);\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n onComplete(val);\n }\n return true;\n }\n\n return false;\n};\n\nexports = ForwardChannelRequestPool;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Generics method for collection-like classes and objects.\n *\n *\n * This file contains functions to work with collections. It supports using\n * Map, Set, Array and Object and other classes that implement collection-like\n * methods.\n * @suppress {strictMissingProperties}\n */\n\n\ngoog.provide('goog.structs');\n\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n// We treat an object as a dictionary if it has getKeys or it is an object that\n// isn't arrayLike.\n\n\n/**\n * Returns the number of values in the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {number} The number of values in the collection-like object.\n */\ngoog.structs.getCount = function(col) {\n 'use strict';\n if (col.getCount && typeof col.getCount == 'function') {\n return col.getCount();\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return col.length;\n }\n return goog.object.getCount(col);\n};\n\n\n/**\n * Returns the values of the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {!Array<?>} The values in the collection-like object.\n */\ngoog.structs.getValues = function(col) {\n 'use strict';\n if (col.getValues && typeof col.getValues == 'function') {\n return col.getValues();\n }\n // ES6 Map and Set both define a values function that returns an iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if ((typeof Map !== 'undefined' && col instanceof Map) ||\n (typeof Set !== 'undefined' && col instanceof Set)) {\n return Array.from(col.values());\n }\n if (typeof col === 'string') {\n return col.split('');\n }\n if (goog.isArrayLike(col)) {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(col[i]);\n }\n return rv;\n }\n return goog.object.getValues(col);\n};\n\n\n/**\n * Returns the keys of the collection. Some collections have no notion of\n * keys/indexes and this function will return undefined in those cases.\n * @param {Object} col The collection-like object.\n * @return {!Array|undefined} The keys in the collection.\n */\ngoog.structs.getKeys = function(col) {\n 'use strict';\n if (col.getKeys && typeof col.getKeys == 'function') {\n return col.getKeys();\n }\n // if we have getValues but no getKeys we know this is a key-less collection\n if (col.getValues && typeof col.getValues == 'function') {\n return undefined;\n }\n // ES6 Map and Set both define a keys function that returns an iterator. For\n // Sets this iterates over the same values as the values iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if (typeof Map !== 'undefined' && col instanceof Map) {\n return Array.from(col.keys());\n }\n // Unlike the native Set, goog.structs.Set does not expose keys as the values.\n if (typeof Set !== 'undefined' && col instanceof Set) {\n return undefined;\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(i);\n }\n return rv;\n }\n\n return goog.object.getKeys(col);\n};\n\n\n/**\n * Whether the collection contains the given value. This is O(n) and uses\n * equals (==) to test the existence.\n * @param {Object} col The collection-like object.\n * @param {*} val The value to check for.\n * @return {boolean} True if the map contains the value.\n */\ngoog.structs.contains = function(col, val) {\n 'use strict';\n if (col.contains && typeof col.contains == 'function') {\n return col.contains(val);\n }\n if (col.containsValue && typeof col.containsValue == 'function') {\n return col.containsValue(val);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\n }\n return goog.object.containsValue(col, val);\n};\n\n\n/**\n * Whether the collection is empty.\n * @param {Object} col The collection-like object.\n * @return {boolean} True if empty.\n */\ngoog.structs.isEmpty = function(col) {\n 'use strict';\n if (col.isEmpty && typeof col.isEmpty == 'function') {\n return col.isEmpty();\n }\n\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\n // string as\n // collection and as such even whitespace matters\n\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return /** @type {!Array<?>} */ (col).length === 0;\n }\n return goog.object.isEmpty(col);\n};\n\n\n/**\n * Removes all the elements from the collection.\n * @param {Object} col The collection-like object.\n * @return {void}\n */\ngoog.structs.clear = function(col) {\n 'use strict';\n // NOTE(arv): This should not contain strings because strings are immutable\n if (col.clear && typeof col.clear == 'function') {\n col.clear();\n } else if (goog.isArrayLike(col)) {\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\n } else {\n goog.object.clear(col);\n }\n};\n\n\n/**\n * Calls a function for each value in a collection. The function takes\n * three arguments; the value, the key and the collection.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\n * This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and the return value is irrelevant.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {void}\n * @template T,S\n * @deprecated Use a more specific method, e.g. native Array.prototype.forEach,\n * or for-of.\n */\ngoog.structs.forEach = function(col, f, opt_obj) {\n 'use strict';\n if (col.forEach && typeof col.forEach == 'function') {\n col.forEach(f, opt_obj);\n } else if (goog.isArrayLike(col) || typeof col === 'string') {\n Array.prototype.forEach.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n } else {\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\n }\n }\n};\n\n\n/**\n * Calls a function for every value in the collection. When a call returns true,\n * adds the value to a new collection (Array is returned by default).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and should return a Boolean. If the\n * return value is true the value is added to the result collection. If it\n * is false the value is not included.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object|!Array<?>} A new collection where the passed values are\n * present. If col is a key-less collection an array is returned. If col\n * has keys and values a plain old JS object is returned.\n * @template T,S\n */\ngoog.structs.filter = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.filter == 'function') {\n return col.filter(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.filter.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\n rv[keys[i]] = values[i];\n }\n }\n } else {\n // We should not use Array#filter here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n if (f.call(opt_obj, values[i], undefined, col)) {\n rv.push(values[i]);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Calls a function for every value in the collection and adds the result into a\n * new collection (defaults to creating a new Array).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\n * This function takes 3 arguments (the value, the key or undefined if the\n * collection has no notion of keys, and the collection) and should return\n * something. The result will be used as the value in the new collection.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\n * col is a key-less collection an array is returned. If col has keys and\n * values a plain old JS object is returned.\n * @template T,S,V\n */\ngoog.structs.map = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.map == 'function') {\n return col.map(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.map.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\n }\n } else {\n // We should not use Array#map here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\n }\n }\n return rv;\n};\n\n\n/**\n * Calls f for each value in a collection. If any call returns true this returns\n * true (without checking the rest). If all returns false this returns false.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or undefined\n * if the collection has no notion of keys, and the collection) and should\n * return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if any value passes the test.\n * @template T,S\n */\ngoog.structs.some = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.some == 'function') {\n return col.some(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.some.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Calls f for each value in a collection. If all calls return true this return\n * true this returns true. If any returns false this returns false at this point\n * and does not continue to check the remaining values.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or\n * undefined if the collection has no notion of keys, and the collection)\n * and should return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if all key-value pairs pass the test.\n * @template T,S\n */\ngoog.structs.every = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.every == 'function') {\n return col.every(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.every.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple utilities for dealing with URI strings.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * This is intended to be a lightweight alternative to constructing goog.Uri\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\n * of how much of its functionality you use, this is designed to be a set of\n * mostly-independent utilities so that the compiler includes only what is\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\n * 1.5k post-gzip. To ensure the savings remain, future developers should\n * avoid adding new functionality to existing functions, but instead create\n * new ones and factor out shared code.\n *\n * Many of these utilities have limited functionality, tailored to common\n * cases. The query parameter utilities assume that the parameter keys are\n * already encoded, since most keys are compile-time alphanumeric strings. The\n * query parameter mutation utilities also do not tolerate fragment identifiers.\n *\n * By design, these functions can be slower than goog.Uri equivalents.\n * Repeated calls to some of functions may be quadratic in behavior for IE,\n * although the effect is somewhat limited given the 2kb limit.\n *\n * One advantage of the limited functionality here is that this approach is\n * less sensitive to differences in URI encodings than goog.Uri, since these\n * functions operate on strings directly, rather than decoding them and\n * then re-encoding.\n *\n * Uses features of RFC 3986 for parsing/formatting URIs:\n * http://www.ietf.org/rfc/rfc3986.txt\n */\n\ngoog.provide('goog.uri.utils');\ngoog.provide('goog.uri.utils.ComponentIndex');\ngoog.provide('goog.uri.utils.QueryArray');\ngoog.provide('goog.uri.utils.QueryValue');\ngoog.provide('goog.uri.utils.StandardQueryParam');\n\ngoog.require('goog.asserts');\ngoog.require('goog.string');\n\n\n/**\n * Character codes inlined to avoid object allocations due to charCode.\n * @enum {number}\n * @private\n */\ngoog.uri.utils.CharCode_ = {\n AMPERSAND: 38,\n EQUAL: 61,\n HASH: 35,\n QUESTION: 63\n};\n\n\n/**\n * Builds a URI string from already-encoded parts.\n *\n * No encoding is performed. Any component may be omitted as either null or\n * undefined.\n *\n * @param {?string=} opt_scheme The scheme such as 'http'.\n * @param {?string=} opt_userInfo The user name before the '@'.\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\n * URI-encoded.\n * @param {(string|number|null)=} opt_port The port number.\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\n * empty, it must begin with a slash.\n * @param {?string=} opt_queryData The URI-encoded query data.\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\n * @return {string} The fully combined URI.\n */\ngoog.uri.utils.buildFromEncodedParts = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\n opt_fragment) {\n 'use strict';\n var out = '';\n\n if (opt_scheme) {\n out += opt_scheme + ':';\n }\n\n if (opt_domain) {\n out += '//';\n\n if (opt_userInfo) {\n out += opt_userInfo + '@';\n }\n\n out += opt_domain;\n\n if (opt_port) {\n out += ':' + opt_port;\n }\n }\n\n if (opt_path) {\n out += opt_path;\n }\n\n if (opt_queryData) {\n out += '?' + opt_queryData;\n }\n\n if (opt_fragment) {\n out += '#' + opt_fragment;\n }\n\n return out;\n};\n\n\n/**\n * A regular expression for breaking a URI into its component parts.\n *\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\n * disambiguation method used by POSIX regular expressions, it is natural and\n * commonplace to use a regular expression for parsing the potential five\n * components of a URI reference.\n *\n * The following line is the regular expression for breaking-down a\n * well-formed URI reference into its components.\n *\n * <pre>\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n * 12 3 4 5 6 7 8 9\n * </pre>\n *\n * The numbers in the second line above are only to assist readability; they\n * indicate the reference points for each subexpression (i.e., each paired\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\n * For example, matching the above expression to\n * <pre>\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\n * </pre>\n * results in the following subexpression matches:\n * <pre>\n * $1 = http:\n * $2 = http\n * $3 = //www.ics.uci.edu\n * $4 = www.ics.uci.edu\n * $5 = /pub/ietf/uri/\n * $6 = <undefined>\n * $7 = <undefined>\n * $8 = #Related\n * $9 = Related\n * </pre>\n * where <undefined> indicates that the component is not present, as is the\n * case for the query component in the above example. Therefore, we can\n * determine the value of the five components as\n * <pre>\n * scheme = $2\n * authority = $4\n * path = $5\n * query = $7\n * fragment = $9\n * </pre>\n *\n * The regular expression has been modified slightly to expose the\n * userInfo, domain, and port separately from the authority.\n * The modified version yields\n * <pre>\n * $1 = http scheme\n * $2 = <undefined> userInfo -\\\n * $3 = www.ics.uci.edu domain | authority\n * $4 = <undefined> port -/\n * $5 = /pub/ietf/uri/ path\n * $6 = <undefined> query without ?\n * $7 = Related fragment without #\n * </pre>\n *\n * TODO(user): separate out the authority terminating characters once this\n * file is moved to ES6.\n * @type {!RegExp}\n * @private\n */\ngoog.uri.utils.splitRe_ = new RegExp(\n '^' + // Anchor against the entire string.\n '(?:' +\n '([^:/?#.]+)' + // scheme - ignore special characters\n // used by other URL parts such as :,\n // ?, /, #, and .\n ':)?' +\n '(?://' +\n '(?:([^\\\\\\\\/?#]*)@)?' + // userInfo\n '([^\\\\\\\\/?#]*?)' + // domain\n '(?::([0-9]+))?' + // port\n '(?=[\\\\\\\\/?#]|$)' + // authority-terminating character.\n ')?' +\n '([^?#]+)?' + // path\n '(?:\\\\?([^#]*))?' + // query\n '(?:#([\\\\s\\\\S]*))?' + // fragment. Can't use '.*' with 's' flag as Firefox\n // doesn't support the flag, and can't use an\n // \"everything set\" ([^]) as IE10 doesn't match any\n // characters with it.\n '$');\n\n\n/**\n * The index of each URI component in the return value of goog.uri.utils.split.\n * @enum {number}\n */\ngoog.uri.utils.ComponentIndex = {\n SCHEME: 1,\n USER_INFO: 2,\n DOMAIN: 3,\n PORT: 4,\n PATH: 5,\n QUERY_DATA: 6,\n FRAGMENT: 7\n};\n\n/**\n * @type {?function(string)}\n * @private\n */\ngoog.uri.utils.urlPackageSupportLoggingHandler_ = null;\n\n/**\n * @param {?function(string)} handler The handler function to call when a URI\n * with a protocol that is better supported by the Closure URL package is\n * detected.\n */\ngoog.uri.utils.setUrlPackageSupportLoggingHandler = function(handler) {\n 'use strict';\n goog.uri.utils.urlPackageSupportLoggingHandler_ = handler;\n};\n\n/**\n * Splits a URI into its component parts.\n *\n * Each component can be accessed via the component indices; for example:\n * <pre>\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\n * </pre>\n *\n * @param {string} uri The URI string to examine.\n * @return {!Array<string|undefined>} Each component still URI-encoded.\n * Each component that is present will contain the encoded value, whereas\n * components that are not present will be undefined or empty, depending\n * on the browser's regular expression implementation. Never null, since\n * arbitrary strings may still look like path names.\n */\ngoog.uri.utils.split = function(uri) {\n 'use strict';\n // See @return comment -- never null.\n var result = /** @type {!Array<string|undefined>} */ (\n uri.match(goog.uri.utils.splitRe_));\n if (goog.uri.utils.urlPackageSupportLoggingHandler_ &&\n ['http', 'https', 'ws', 'wss',\n 'ftp'].indexOf(result[goog.uri.utils.ComponentIndex.SCHEME]) >= 0) {\n goog.uri.utils.urlPackageSupportLoggingHandler_(uri);\n }\n return result;\n};\n\n\n/**\n * @param {?string} uri A possibly null string.\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\n * reserved characters will not be removed.\n * @return {?string} The string URI-decoded, or null if uri is null.\n * @private\n */\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\n 'use strict';\n if (!uri) {\n return uri;\n }\n\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\n};\n\n\n/**\n * Gets a URI component by index.\n *\n * It is preferred to use the getPathEncoded() variety of functions ahead,\n * since they are more readable.\n *\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\n * @param {string} uri The URI to examine.\n * @return {?string} The still-encoded component, or null if the component\n * is not present.\n * @private\n */\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\n 'use strict';\n // Convert undefined, null, and empty string into null.\n return goog.uri.utils.split(uri)[componentIndex] || null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The protocol or scheme, or null if none. Does not\n * include trailing colons or slashes.\n */\ngoog.uri.utils.getScheme = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.SCHEME, uri);\n};\n\n\n/**\n * Gets the effective scheme for the URL. If the URL is relative then the\n * scheme is derived from the page's location.\n * @param {string} uri The URI to examine.\n * @return {string} The protocol or scheme, always lower case.\n */\ngoog.uri.utils.getEffectiveScheme = function(uri) {\n 'use strict';\n var scheme = goog.uri.utils.getScheme(uri);\n if (!scheme && goog.global.self && goog.global.self.location) {\n var protocol = goog.global.self.location.protocol;\n scheme = protocol.substr(0, protocol.length - 1);\n }\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\n // All other browsers with web workers support self.location from the worker.\n return scheme ? scheme.toLowerCase() : '';\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The user name still encoded, or null if none.\n */\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded user info, or null if none.\n */\ngoog.uri.utils.getUserInfo = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getUserInfoEncoded(uri));\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The domain name still encoded, or null if none.\n */\ngoog.uri.utils.getDomainEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded domain, or null if none.\n */\ngoog.uri.utils.getDomain = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?number} The port number, or null if none.\n */\ngoog.uri.utils.getPort = function(uri) {\n 'use strict';\n // Coerce to a number. If the result of getComponentByIndex_ is null or\n // non-numeric, the number coersion yields NaN. This will then return\n // null for all non-numeric cases (though also zero, which isn't a relevant\n // port number).\n return Number(\n goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\n null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The path still encoded, or null if none. Includes the\n * leading slash, if any.\n */\ngoog.uri.utils.getPathEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PATH, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded path, or null if none. Includes the leading\n * slash, if any.\n */\ngoog.uri.utils.getPath = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The query data still encoded, or null if none. Does not\n * include the question mark itself.\n */\ngoog.uri.utils.getQueryData = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The fragment identifier, or null if none. Does not\n * include the hash mark itself.\n */\ngoog.uri.utils.getFragmentEncoded = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? null : uri.substr(hashIndex + 1);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @param {?string} fragment The encoded fragment identifier, or null if none.\n * Does not include the hash mark itself.\n * @return {string} The URI with the fragment set.\n */\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\n 'use strict';\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded fragment identifier, or null if none. Does\n * not include the hash mark.\n */\ngoog.uri.utils.getFragment = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getFragmentEncoded(uri));\n};\n\n\n/**\n * Extracts everything up to the port of the URI.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getHost = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Returns the origin for a given URL.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getOrigin = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Extracts the path of the URL and everything after.\n * @param {string} uri The URI string.\n * @return {string} The URI, starting at the path and including the query\n * parameters and fragment identifier.\n */\ngoog.uri.utils.getPathAndAfter = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Gets the URI with the fragment identifier removed.\n * @param {string} uri The URI to examine.\n * @return {string} Everything preceding the hash mark.\n */\ngoog.uri.utils.removeFragment = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? uri : uri.substr(0, hashIndex);\n};\n\n\n/**\n * Ensures that two URI's have the exact same domain, scheme, and port.\n *\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\n * suitable for checking against the browser's same-origin policy.\n *\n * @param {string} uri1 The first URI.\n * @param {string} uri2 The second URI.\n * @return {boolean} Whether they have the same scheme, domain and port.\n */\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\n 'use strict';\n var pieces1 = goog.uri.utils.split(uri1);\n var pieces2 = goog.uri.utils.split(uri2);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n/**\n * Asserts that there are no fragment or query identifiers, only in uncompiled\n * mode.\n * @param {string} uri The URI to examine.\n * @private\n */\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\n 'use strict';\n goog.asserts.assert(\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\n uri);\n};\n\n\n/**\n * Supported query parameter values by the parameter serializing utilities.\n *\n * If a value is null or undefined, the key-value pair is skipped, as an easy\n * way to omit parameters conditionally. Non-array parameters are converted\n * to a string and URI encoded. Array values are expanded into multiple\n * &key=value pairs, with each element stringized and URI-encoded.\n *\n * @typedef {*}\n */\ngoog.uri.utils.QueryValue;\n\n\n/**\n * An array representing a set of query parameters with alternating keys\n * and values.\n *\n * Keys are assumed to be URI encoded already and live at even indices. See\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\n *\n * Example:\n * <pre>\n * var data = [\n * // Simple param: ?name=BobBarker\n * 'name', 'BobBarker',\n * // Conditional param -- may be omitted entirely.\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\n * 'house', ['LosAngeles', 'NewYork', null]\n * ];\n * </pre>\n *\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\n */\ngoog.uri.utils.QueryArray;\n\n\n/**\n * Parses encoded query parameters and calls callback function for every\n * parameter found in the string.\n *\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\n * that “…&=&…” and “…&&…” will result in an empty key and value.\n *\n * @param {string} encodedQuery Encoded query string excluding question mark at\n * the beginning.\n * @param {function(string, string)} callback Function called for every\n * parameter found in query string. The first argument (name) will not be\n * urldecoded (so the function is consistent with buildQueryData), but the\n * second will. If the parameter has no value (i.e. “=” was not present)\n * the second argument (value) will be an empty string.\n */\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\n 'use strict';\n if (!encodedQuery) {\n return;\n }\n var pairs = encodedQuery.split('&');\n for (var i = 0; i < pairs.length; i++) {\n var indexOfEquals = pairs[i].indexOf('=');\n var name = null;\n var value = null;\n if (indexOfEquals >= 0) {\n name = pairs[i].substring(0, indexOfEquals);\n value = pairs[i].substring(indexOfEquals + 1);\n } else {\n name = pairs[i];\n }\n callback(name, value ? goog.string.urlDecode(value) : '');\n }\n};\n\n\n/**\n * Split the URI into 3 parts where the [1] is the queryData without a leading\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\n * ['http://foo.com/bar','a=b','#abc'].\n * @param {string} uri The URI to parse.\n * @return {!Array<string>} An array representation of uri of length 3 where the\n * middle value is the queryData without a leading '?'.\n * @private\n */\ngoog.uri.utils.splitQueryData_ = function(uri) {\n 'use strict';\n // Find the query data and hash.\n var hashIndex = uri.indexOf('#');\n if (hashIndex < 0) {\n hashIndex = uri.length;\n }\n var questionIndex = uri.indexOf('?');\n var queryData;\n if (questionIndex < 0 || questionIndex > hashIndex) {\n questionIndex = hashIndex;\n queryData = '';\n } else {\n queryData = uri.substring(questionIndex + 1, hashIndex);\n }\n return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];\n};\n\n\n/**\n * Join an array created by splitQueryData_ back into a URI.\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\n * @return {string} The joined URI.\n * @private\n */\ngoog.uri.utils.joinQueryData_ = function(parts) {\n 'use strict';\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\n};\n\n\n/**\n * @param {string} queryData\n * @param {string} newData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\n 'use strict';\n if (!newData) {\n return queryData;\n }\n return queryData ? queryData + '&' + newData : newData;\n};\n\n\n/**\n * @param {string} uri\n * @param {string} queryData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\n 'use strict';\n if (!queryData) {\n return uri;\n }\n var parts = goog.uri.utils.splitQueryData_(uri);\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Appends key=value pairs to an array, supporting multi-valued objects.\n * @param {*} key The key prefix.\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\n * should be appended.\n * @private\n */\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\n 'use strict';\n goog.asserts.assertString(key);\n if (Array.isArray(value)) {\n // Convince the compiler it's an array.\n goog.asserts.assertArray(value);\n for (var j = 0; j < value.length; j++) {\n // Convert to string explicitly, to short circuit the null and array\n // logic in this function -- this ensures that null and undefined get\n // written as literal 'null' and 'undefined', and arrays don't get\n // expanded out but instead encoded in the default way.\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\n }\n } else if (value != null) {\n // Skip a top-level null or undefined entirely.\n pairs.push(\n key +\n // Check for empty string. Zero gets encoded into the url as literal\n // strings. For empty string, skip the equal sign, to be consistent\n // with UriBuilder.java.\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\n }\n};\n\n\n/**\n * Builds a query data string from a sequence of alternating keys and values.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\n * Alternating keys and values. See the QueryArray typedef.\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\n 'use strict';\n goog.asserts.assert(\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\n 'goog.uri.utils: Key/value lists must be even in length.');\n\n var params = [];\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\n var key = /** @type {string} */ (keysAndValues[i]);\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Builds a query data string from a map.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\n * are URI-encoded parameter keys, and the values are arbitrary types\n * or arrays. Keys with a null value are dropped.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\n 'use strict';\n var params = [];\n for (var key in map) {\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Appends URI parameters to an existing URI.\n *\n * The variable arguments may contain alternating keys and values. Keys are\n * assumed to be already URI encoded. The values should not be URI-encoded,\n * and will instead be encoded by this function.\n * <pre>\n * appendParams('http://www.foo.com?existing=true',\n * 'key1', 'value1',\n * 'key2', 'value?willBeEncoded',\n * 'key3', ['valueA', 'valueB', 'valueC'],\n * 'key4', null);\n * result: 'http://www.foo.com?existing=true&' +\n * 'key1=value1&' +\n * 'key2=value%3FwillBeEncoded&' +\n * 'key3=valueA&key3=valueB&key3=valueC'\n * </pre>\n *\n * A single call to this function will not exhibit quadratic behavior in IE,\n * whereas multiple repeated calls may, although the effect is limited by\n * fact that URL's generally can't exceed 2kb.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\n * var_args\n * An array or argument list conforming to goog.uri.utils.QueryArray.\n * @return {string} The URI with all query parameters added.\n */\ngoog.uri.utils.appendParams = function(uri, var_args) {\n 'use strict';\n var queryData = arguments.length == 2 ?\n goog.uri.utils.buildQueryData(arguments[1], 0) :\n goog.uri.utils.buildQueryData(arguments, 1);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends query parameters from a map.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\n * Keys with a null value are dropped.\n * @return {string} The new parameters.\n */\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\n 'use strict';\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends a single URI parameter.\n *\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\n * way string append works, though it should be limited given the 2kb limit.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} key The key, which must already be URI encoded.\n * @param {*=} opt_value The value, which will be stringized and encoded\n * (assumed not already to be encoded). If omitted, undefined, or null, the\n * key will be added as a valueless parameter.\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\n 'use strict';\n var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\n};\n\n\n/**\n * Finds the next instance of a query parameter with the specified name.\n *\n * Does not instantiate any objects.\n *\n * @param {string} uri The URI to search. May contain a fragment identifier\n * if opt_hashIndex is specified.\n * @param {number} startIndex The index to begin searching for the key at. A\n * match may be found even if this is one character after the ampersand.\n * @param {string} keyEncoded The URI-encoded key.\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\n * mark is present, it should be its index, otherwise it should be the\n * length of the string.\n * @return {number} The position of the first character in the key's name,\n * immediately after either a question mark or a dot.\n * @private\n */\ngoog.uri.utils.findParam_ = function(\n uri, startIndex, keyEncoded, hashOrEndIndex) {\n 'use strict';\n var index = startIndex;\n var keyLength = keyEncoded.length;\n\n // Search for the key itself and post-filter for surronuding punctuation,\n // rather than expensively building a regexp.\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\n index < hashOrEndIndex) {\n var precedingChar = uri.charCodeAt(index - 1);\n // Ensure that the preceding character is '&' or '?'.\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\n // Ensure the following character is '&', '=', '#', or NaN\n // (end of string).\n var followingChar = uri.charCodeAt(index + keyLength);\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n followingChar == goog.uri.utils.CharCode_.HASH) {\n return index;\n }\n }\n index += keyLength + 1;\n }\n\n return -1;\n};\n\n\n/**\n * Regular expression for finding a hash mark or end of string.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\n\n\n/**\n * Determines if the URI contains a specific key.\n *\n * Performs no object instantiations.\n *\n * @param {string} uri The URI to process. May contain a fragment\n * identifier.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {boolean} Whether the key is present.\n */\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\n 'use strict';\n return goog.uri.utils.findParam_(\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\n};\n\n\n/**\n * Gets the first value of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {?string} The first value of the parameter (URI-decoded), or null\n * if the parameter is not found.\n */\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var foundIndex =\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\n\n if (foundIndex < 0) {\n return null;\n } else {\n var endPosition = uri.indexOf('&', foundIndex);\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\n endPosition = hashOrEndIndex;\n }\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n // Use substr, because it (unlike substring) will return empty string\n // if foundIndex > endPosition.\n return goog.string.urlDecode(\n uri.substr(foundIndex, endPosition - foundIndex));\n }\n};\n\n\n/**\n * Gets all values of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {!Array<string>} All URI-decoded values with the given key.\n * If the key is not found, this will have length 0, but never be null.\n */\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var result = [];\n\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Find where this parameter ends, either the '&' or the end of the\n // query parameters.\n position = uri.indexOf('&', foundIndex);\n if (position < 0 || position > hashOrEndIndex) {\n position = hashOrEndIndex;\n }\n\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n // Use substr, because it (unlike substring) will return empty string\n // if foundIndex > position.\n result.push(\n goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));\n }\n\n return result;\n};\n\n\n/**\n * Regexp to find trailing question marks and ampersands.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\n\n\n/**\n * Removes all instances of a query parameter.\n * @param {string} uri The URI to process. Must not contain a fragment.\n * @param {string} keyEncoded The URI-encoded key.\n * @return {string} The URI with all instances of the parameter removed.\n */\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var buffer = [];\n\n // Look for a query parameter.\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Get the portion of the query string up to, but not including, the ?\n // or & starting the parameter.\n buffer.push(uri.substring(position, foundIndex));\n // Progress to immediately after the '&'. If not found, go to the end.\n // Avoid including the hash mark.\n position = Math.min(\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\n }\n\n // Append everything that is remaining.\n buffer.push(uri.substr(position));\n\n // Join the buffer, and remove trailing punctuation that remains.\n return buffer.join('').replace(\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\n};\n\n\n/**\n * Replaces all existing definitions of a parameter with a single definition.\n *\n * Repeated calls to this can exhibit quadratic behavior due to the need to\n * find existing instances and reconstruct the string, though it should be\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\n * to update multiple parameters in bulk.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} keyEncoded The key, which must already be URI encoded.\n * @param {*} value The value, which will be stringized and encoded (assumed\n * not already to be encoded).\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\n 'use strict';\n return goog.uri.utils.appendParam(\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\n};\n\n\n/**\n * Effeciently set or remove multiple query parameters in a URI. Order of\n * unchanged parameters will not be modified, all updated parameters will be\n * appended to the end of the query. Params with values of null or undefined are\n * removed.\n *\n * @param {string} uri The URI to process.\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\n * parameters to update. If null or undefined, the param will be removed.\n * @return {string} An updated URI where the query data has been updated with\n * the params.\n */\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\n 'use strict';\n var parts = goog.uri.utils.splitQueryData_(uri);\n var queryData = parts[1];\n var buffer = [];\n if (queryData) {\n queryData.split('&').forEach(function(pair) {\n 'use strict';\n var indexOfEquals = pair.indexOf('=');\n var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;\n if (!params.hasOwnProperty(name)) {\n buffer.push(pair);\n }\n });\n }\n parts[1] = goog.uri.utils.appendQueryData_(\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Generates a URI path using a given URI and a path with checks to\n * prevent consecutive \"//\". The baseUri passed in must not contain\n * query or fragment identifiers. The path to append may not contain query or\n * fragment identifiers.\n *\n * @param {string} baseUri URI to use as the base.\n * @param {string} path Path to append.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.appendPath = function(baseUri, path) {\n 'use strict';\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\n\n // Remove any trailing '/'\n if (goog.string.endsWith(baseUri, '/')) {\n baseUri = baseUri.substr(0, baseUri.length - 1);\n }\n // Remove any leading '/'\n if (goog.string.startsWith(path, '/')) {\n path = path.substr(1);\n }\n return '' + baseUri + '/' + path;\n};\n\n\n/**\n * Replaces the path.\n * @param {string} uri URI to use as the base.\n * @param {string} path New path.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.setPath = function(uri, path) {\n 'use strict';\n // Add any missing '/'.\n if (!goog.string.startsWith(path, '/')) {\n path = '/' + path;\n }\n var parts = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n parts[goog.uri.utils.ComponentIndex.SCHEME],\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\n parts[goog.uri.utils.ComponentIndex.PORT], path,\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Standard supported query parameters.\n * @enum {string}\n */\ngoog.uri.utils.StandardQueryParam = {\n\n /** Unused parameter for unique-ifying. */\n RANDOM: 'zx'\n};\n\n\n/**\n * Sets the zx parameter of a URI to a random value.\n * @param {string} uri Any URI.\n * @return {string} That URI with the \"zx\" parameter added or replaced to\n * contain a random string.\n */\ngoog.uri.utils.makeUnique = function(uri) {\n 'use strict';\n return goog.uri.utils.setParam(\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\n goog.string.getRandomString());\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface and shared data structures for implementing\n * different wire protocol versions.\n */\ngoog.provide('goog.labs.net.webChannel.Wire');\ngoog.provide('goog.labs.net.webChannel.Wire.QueuedMap');\n\n\n\ngoog.require('goog.collections.maps');\n\n\n\n/**\n * The interface class.\n * @interface\n */\ngoog.labs.net.webChannel.Wire = class {\n constructor() {}\n};\n\n\n/**\n * The latest protocol version that this class supports. We request this version\n * from the server when opening the connection. Should match\n * LATEST_CHANNEL_VERSION on the server code.\n * @type {number}\n */\ngoog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION = 8;\n\n\n/**\n * The JSON field key for the raw data wrapper object.\n * @type {string}\n */\ngoog.labs.net.webChannel.Wire.RAW_DATA_KEY = '__data__';\n\n\n\n/**\n * Simple container class for a (mapId, map) pair.\n */\ngoog.labs.net.webChannel.Wire.QueuedMap = class {\n /**\n * @param {number} mapId The id for this map.\n * @param {!Object|!goog.collections.maps.MapLike} map The map itself.\n * @param {!Object=} opt_context The context associated with the map.\n */\n constructor(mapId, map, opt_context) {\n 'use strict';\n /**\n * The id for this map.\n * @type {number}\n */\n this.mapId = mapId;\n\n /**\n * The map itself.\n * @type {!Object|!goog.collections.maps.MapLike}\n */\n this.map = map;\n\n /**\n * The context for the map.\n * @type {Object}\n */\n this.context = opt_context || null;\n }\n\n /**\n * @return {number|undefined} the size of the raw JSON message or\n * undefined if the message is not encoded as a raw JSON message\n */\n getRawDataSize() {\n 'use strict';\n if (goog.labs.net.webChannel.Wire.RAW_DATA_KEY in this.map) {\n const data = this.map[goog.labs.net.webChannel.Wire.RAW_DATA_KEY];\n if (typeof data === 'string') {\n return data.length;\n }\n }\n\n return undefined;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for creating functions. Loosely inspired by these\n * java classes from the Guava library:\n * com.google.common.base.Functions\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\n *\n * com.google.common.base.Predicates\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\n *\n * More about these can be found at\n * https://github.com/google/guava/wiki/FunctionalExplained\n */\n\n\ngoog.provide('goog.functions');\n\n\n/**\n * Creates a function that always returns the same value.\n * @param {T} retValue The value to return.\n * @return {function():T} The new function.\n * @template T\n */\ngoog.functions.constant = function(retValue) {\n 'use strict';\n return function() {\n 'use strict';\n return retValue;\n };\n};\n\n\n/**\n * Always returns false.\n * @type {function(...): boolean}\n */\ngoog.functions.FALSE = function() {\n 'use strict';\n return false;\n};\n\n\n/**\n * Always returns true.\n * @type {function(...): boolean}\n */\ngoog.functions.TRUE = function() {\n 'use strict';\n return true;\n};\n\n\n/**\n * Always returns `null`.\n * @type {function(...): null}\n */\ngoog.functions.NULL = function() {\n 'use strict';\n return null;\n};\n\n\n/**\n * Always returns `undefined`.\n * @type {function(...): undefined}\n */\ngoog.functions.UNDEFINED = function() {\n return undefined;\n};\n\n/**\n * Always returns `undefined` (loosely-typed version).\n * @type {!Function}\n */\ngoog.functions.EMPTY = /** @type {?} */ (goog.functions.UNDEFINED);\n\n\n/**\n * A simple function that returns the first argument of whatever is passed\n * into it.\n * @param {T=} opt_returnValue The single value that will be returned.\n * @param {...*} var_args Optional trailing arguments. These are ignored.\n * @return {T} The first argument passed in, or undefined if nothing was passed.\n * @template T\n */\ngoog.functions.identity = function(opt_returnValue, var_args) {\n 'use strict';\n return opt_returnValue;\n};\n\n\n/**\n * Creates a function that always throws an error with the given message.\n * @param {string} message The error message.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.error = function(message) {\n 'use strict';\n return function() {\n 'use strict';\n throw new Error(message);\n };\n};\n\n\n/**\n * Creates a function that throws the given object.\n * @param {*} err An object to be thrown.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.fail = function(err) {\n 'use strict';\n return function() {\n 'use strict';\n throw err;\n };\n};\n\n\n/**\n * Given a function, create a function that keeps opt_numArgs arguments and\n * silently discards all additional arguments.\n * @param {Function} f The original function.\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\n * @return {!Function} A version of f that only keeps the first opt_numArgs\n * arguments.\n */\ngoog.functions.lock = function(f, opt_numArgs) {\n 'use strict';\n opt_numArgs = opt_numArgs || 0;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\n };\n};\n\n\n/**\n * Creates a function that returns its nth argument.\n * @param {number} n The position of the return argument.\n * @return {!Function} A new function.\n */\ngoog.functions.nth = function(n) {\n 'use strict';\n return function() {\n 'use strict';\n return arguments[n];\n };\n};\n\n\n/**\n * Like goog.partial(), except that arguments are added after arguments to the\n * returned function.\n *\n * Usage:\n * function f(arg1, arg2, arg3, arg4) { ... }\n * var g = goog.functions.partialRight(f, arg3, arg4);\n * g(arg1, arg2);\n *\n * @param {!Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn\n * at the end.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.functions.partialRight = function(fn, var_args) {\n 'use strict';\n const rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n 'use strict';\n // Even in strict mode, IE10/11 and Edge (non-Chromium) use global context\n // when free-calling functions. To catch cases where people were using this\n // erroneously, we explicitly change the context to undefined to match\n // strict mode specifications.\n let self = /** @type {*} */ (this);\n if (self === goog.global) {\n self = undefined;\n }\n const newArgs = Array.prototype.slice.call(arguments);\n newArgs.push.apply(newArgs, rightArgs);\n return fn.apply(self, newArgs);\n };\n};\n\n\n/**\n * Given a function, create a new function that swallows its return value\n * and replaces it with a new one.\n * @param {Function} f A function.\n * @param {T} retValue A new return value.\n * @return {function(...?):T} A new function.\n * @template T\n */\ngoog.functions.withReturnValue = function(f, retValue) {\n 'use strict';\n return goog.functions.sequence(f, goog.functions.constant(retValue));\n};\n\n\n/**\n * Creates a function that returns whether its argument equals the given value.\n *\n * Example:\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\n *\n * @param {*} value The value to compare to.\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\n * comparison rather than a strict (===) one. Defaults to false.\n * @return {function(*):boolean} The new function.\n */\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\n 'use strict';\n return function(other) {\n 'use strict';\n return opt_useLooseComparison ? (value == other) : (value === other);\n };\n};\n\n\n/**\n * Creates the composition of the functions passed in.\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\n * @param {function(...?):T} fn The final function.\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):T} The composition of all inputs.\n * @template T\n */\ngoog.functions.compose = function(fn, var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (let i = length - 2; i >= 0; i--) {\n result = functions[i].call(self, result);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that calls the functions passed in in sequence, and\n * returns the value of the last function. For example,\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\n * @param {...Function} var_args A list of functions.\n * @return {!Function} A function that calls all inputs in sequence.\n */\ngoog.functions.sequence = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n for (let i = 0; i < length; i++) {\n result = functions[i].apply(self, arguments);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that returns true if each of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns false.\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ANDs its component\n * functions.\n */\ngoog.functions.and = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (!functions[i].apply(self, arguments)) {\n return false;\n }\n }\n return true;\n };\n};\n\n\n/**\n * Creates a function that returns true if any of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns true.\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ORs its component\n * functions.\n */\ngoog.functions.or = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (functions[i].apply(self, arguments)) {\n return true;\n }\n }\n return false;\n };\n};\n\n\n/**\n * Creates a function that returns the Boolean opposite of a provided function.\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\n * @param {!Function} f The original function.\n * @return {function(...?):boolean} A function that delegates to f and returns\n * opposite.\n */\ngoog.functions.not = function(f) {\n 'use strict';\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return !f.apply(self, arguments);\n };\n};\n\n\n/**\n * Generic factory function to construct an object given the constructor\n * and the arguments. Intended to be bound to create object factories.\n *\n * Example:\n *\n * var factory = goog.partial(goog.functions.create, Class);\n *\n * @param {function(new:T, ...)} constructor The constructor for the Object.\n * @param {...*} var_args The arguments to be passed to the constructor.\n * @return {T} A new instance of the class given in `constructor`.\n * @template T\n * @deprecated This function does not work with ES6 class constructors. Use\n * arrow functions + spread args instead.\n */\ngoog.functions.create = function(constructor, var_args) {\n 'use strict';\n /**\n * @constructor\n * @final\n */\n const temp = function() {};\n temp.prototype = constructor.prototype;\n\n // obj will have constructor's prototype in its chain and\n // 'obj instanceof constructor' will be true.\n const obj = new temp();\n\n // obj is initialized by constructor.\n // arguments is only array-like so lacks shift(), but can be used with\n // the Array prototype function.\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\n return obj;\n};\n\n\n/**\n * @define {boolean} Whether the return value cache should be used.\n * This should only be used to disable caches when testing.\n */\ngoog.functions.CACHE_RETURN_VALUE =\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\n\n\n/**\n * Gives a wrapper function that caches the return value of a parameterless\n * function when first called.\n *\n * When called for the first time, the given function is called and its\n * return value is cached (thus this is only appropriate for idempotent\n * functions). Subsequent calls will return the cached return value. This\n * allows the evaluation of expensive functions to be delayed until first used.\n *\n * To cache the return values of functions with parameters, see goog.memoize.\n *\n * @param {function():T} fn A function to lazily evaluate.\n * @return {function():T} A wrapped version the function.\n * @template T\n */\ngoog.functions.cacheReturnValue = function(fn) {\n 'use strict';\n let called = false;\n let value;\n\n return function() {\n 'use strict';\n if (!goog.functions.CACHE_RETURN_VALUE) {\n return fn();\n }\n\n if (!called) {\n value = fn();\n called = true;\n }\n\n return value;\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once. All\n * additional calls are no-ops.\n *\n * This is particularly useful for initialization functions\n * that should be called, at most, once.\n *\n * @param {function():*} f Function to call.\n * @return {function():undefined} Wrapped function.\n */\ngoog.functions.once = function(f) {\n 'use strict';\n // Keep a reference to the function that we null out when we're done with\n // it -- that way, the function can be GC'd when we're done with it.\n let inner = f;\n return function() {\n 'use strict';\n if (inner) {\n const tmp = inner;\n inner = null;\n tmp();\n }\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the Nth call will go through.\n *\n * This is particularly useful for batching up repeated actions where the\n * last action should win. This can be used, for example, for refreshing an\n * autocomplete pop-up every so often rather than updating with every keystroke,\n * since the final text typed by the user is the one that should produce the\n * final autocomplete results. For more stateful debouncing with support for\n * pausing, resuming, and canceling debounced actions, use\n * `goog.async.Debouncer`.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to debounce. The function will\n * only be called after the full interval has elapsed since the last call.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.debounce = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n goog.global.clearTimeout(timeout);\n const args = arguments;\n timeout = goog.global.setTimeout(function() {\n 'use strict';\n f.apply(opt_scope, args);\n }, interval);\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times in\n * that interval, both the 1st and the Nth calls will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * the last action should win, but you also don't want to wait until the end of\n * the interval before sending a request out, as it leads to a perception of\n * slowness for the user.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to throttle. The function can\n * only be called once per interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.throttle = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n let shouldFire = false;\n let storedArgs = [];\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n const fire = function() {\n 'use strict';\n timeout = goog.global.setTimeout(handleTimeout, interval);\n let args = storedArgs;\n storedArgs = []; // Avoid a space leak by clearing stored arguments.\n f.apply(opt_scope, args);\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n storedArgs = arguments;\n if (!timeout) {\n fire();\n } else {\n shouldFire = true;\n }\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the 1st call will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * first request is guaranteed to have all the data required to perform the\n * final action, so there's no need to wait until the end of the interval before\n * sending the request out.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to rate-limit. The function will\n * only be called once per interval, and ignored for the remainer of the\n * interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n if (!timeout) {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, arguments);\n }\n });\n};\n\n/**\n * Returns true if the specified value is a function.\n * @param {*} val Variable to test.\n * @return {boolean} Whether variable is a function.\n */\ngoog.functions.isFunction = (val) => {\n return typeof val === 'function';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Defines a class for parsing JSON using the browser's built in\n * JSON library.\n */\n\ngoog.provide('goog.json.NativeJsonProcessor');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json.Processor');\n\n\n\n/**\n * A class that parses and stringifies JSON using the browser's built-in JSON\n * library, if it is available.\n *\n * Note that the native JSON api has subtle differences across browsers, so\n * use this implementation with care. See json_test#assertSerialize\n * for details on the differences from goog.json.\n *\n * This implementation is signficantly faster than goog.json, at least on\n * Chrome. See json_perf.html for a perf test showing the difference.\n *\n * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during\n * serialization.\n * @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during\n * parsing.\n * @constructor\n * @implements {goog.json.Processor}\n * @final\n */\ngoog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) {\n 'use strict';\n goog.asserts.assert(goog.global['JSON'] !== undefined, 'JSON not defined');\n\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n\n /**\n * @type {goog.json.Reviver|null|undefined}\n * @private\n */\n this.reviver_ = opt_reviver;\n};\n\n\n/** @override */\ngoog.json.NativeJsonProcessor.prototype.stringify = function(object) {\n 'use strict';\n return goog.global['JSON'].stringify(object, this.replacer_);\n};\n\n\n/** @override */\ngoog.json.NativeJsonProcessor.prototype.parse = function(s) {\n 'use strict';\n return goog.global['JSON'].parse(s, this.reviver_);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utility functions for managing networking, such as\n * testing network connectivity.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.netUtils');\n\ngoog.require('goog.Uri');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.scope(function() {\n'use strict';\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Default timeout to allow for URI pings.\n * @type {number}\n */\nnetUtils.NETWORK_TIMEOUT = 10000;\n\n\n/**\n * Pings the network with an image URI to check if an error is a server error\n * or user's network error.\n *\n * The caller needs to add a 'rand' parameter to make sure the response is\n * not fulfilled by browser cache.\n *\n * @param {function(boolean)} callback The function to call back with results.\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\n * test.\n */\nnetUtils.testNetwork = function(callback, opt_imageUri) {\n 'use strict';\n let uri = opt_imageUri;\n if (!uri) {\n // default google.com image\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\n\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\n uri.setScheme('https'); // e.g. chrome-extension\n }\n uri.makeUnique();\n }\n\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\n};\n\n\n/**\n * Test loading the given image, retrying if necessary.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @param {number} retries The number of times to retry.\n * @param {!WebChannelDebug} channelDebug The debug object\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\n * between retries - defaults to 0.\n */\nnetUtils.testLoadImageWithRetries = function(\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\n 'use strict';\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\n if (retries == 0) {\n // no more retries, give up\n callback(false);\n return;\n }\n\n const pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\n retries--;\n netUtils.testLoadImage(url, timeout, function(succeeded) {\n 'use strict';\n if (succeeded) {\n callback(true);\n } else {\n // try again\n goog.global.setTimeout(function() {\n 'use strict';\n netUtils.testLoadImageWithRetries(\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\n }, pauseBetweenRetries);\n }\n });\n};\n\n\n/**\n * Test loading the given image.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.testLoadImage = function(url, timeout, callback) {\n 'use strict';\n const channelDebug = new WebChannelDebug();\n channelDebug.debug('TestLoadImage: loading ' + url);\n if (goog.global.Image) {\n const img = new Image();\n img.onload = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\n true, callback);\n img.onerror = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\n false, callback);\n img.onabort = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\n false, callback);\n img.ontimeout = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\n false, callback);\n\n goog.global.setTimeout(function() {\n 'use strict';\n if (img.ontimeout) {\n img.ontimeout();\n }\n }, timeout);\n img.src = url;\n } else {\n // log ERROR_OTHER from environements where Image is not supported\n callback(false);\n }\n};\n\n\n/**\n * Wrap the image callback with debug and cleanup logic.\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\n * @param {!Image} img The image element.\n * @param {string} debugText The debug text.\n * @param {boolean} result The result of image loading.\n * @param {function(boolean)} callback The image callback.\n * @private\n */\nnetUtils.imageCallback_ = function(\n channelDebug, img, debugText, result, callback) {\n 'use strict';\n try {\n channelDebug.debug(debugText);\n netUtils.clearImageCallbacks_(img);\n callback(result);\n } catch (e) {\n channelDebug.dumpException(e);\n }\n};\n\n\n/**\n * Clears handlers to avoid memory leaks.\n * @param {Image} img The image to clear handlers from.\n * @private\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.clearImageCallbacks_ = function(img) {\n 'use strict';\n img.onload = null;\n img.onerror = null;\n img.onabort = null;\n img.ontimeout = null;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.net.FetchXmlHttp');\ngoog.provide('goog.net.FetchXmlHttpFactory');\n\ngoog.require('goog.asserts');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.functions');\ngoog.require('goog.log');\ngoog.require('goog.net.XhrLike');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * @record\n */\ngoog.net.FetchXmlHttpFactoryOptions = function() {\n /**\n * @type {!WorkerGlobalScope|undefined} The Service Worker global scope.\n */\n this.worker;\n\n /**\n * @type {boolean|undefined} Whether to store the FetchXmlHttp response as an\n * array of Uint8Arrays. If this is true then the 'responseType' attribute\n * must be empty.\n */\n this.streamBinaryChunks;\n};\n\n\n\n/**\n * Factory for creating Xhr objects that uses the native fetch() method.\n * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n * @param {!goog.net.FetchXmlHttpFactoryOptions} opts\n * @extends {goog.net.XmlHttpFactory}\n * @struct\n * @constructor\n */\ngoog.net.FetchXmlHttpFactory = function(opts) {\n 'use strict';\n goog.net.FetchXmlHttpFactory.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = opts.worker || null;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = opts.streamBinaryChunks || false;\n\n /** @private {!RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {!RequestCache|undefined} */\n this.cacheMode_ = undefined;\n};\ngoog.inherits(goog.net.FetchXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const instance =\n new goog.net.FetchXmlHttp(this.worker_, this.streamBinaryChunks_);\n if (this.credentialsMode_) {\n instance.setCredentialsMode(this.credentialsMode_);\n }\n if (this.cacheMode_) {\n instance.setCacheMode(this.cacheMode_);\n }\n return instance;\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.internalGetOptions =\n goog.functions.constant({});\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCredentialsMode = function(\n credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n\n/**\n * FetchXmlHttp object constructor.\n * @param {?WorkerGlobalScope} worker\n * @param {boolean} streamBinaryChunks\n * @extends {goog.events.EventTarget}\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n */\ngoog.net.FetchXmlHttp = function(worker, streamBinaryChunks) {\n 'use strict';\n goog.net.FetchXmlHttp.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = streamBinaryChunks;\n\n /** @private {RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {RequestCache|undefined} */\n this.cacheMode_ = undefined;\n\n /**\n * Request state.\n * @type {goog.net.FetchXmlHttp.RequestState}\n */\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n\n /**\n * HTTP status.\n * @type {number}\n */\n this.status = 0;\n\n /**\n * HTTP status string.\n * @type {string}\n */\n this.statusText = '';\n\n /**\n * Content of the response.\n * @type {string|!ArrayBuffer|!Array<!Uint8Array>}\n */\n this.response = '';\n\n /**\n * Content of the response.\n * @type {string}\n */\n this.responseText = '';\n\n /**\n * The type of the response. If this is set to 'arraybuffer' the request will\n * be discrete, streaming is only supported for text encoded requests.\n * @type {string}\n */\n this.responseType = '';\n\n /**\n * Document response entity body.\n * NOTE: This is always null and not supported by this class.\n * @final {null}\n */\n this.responseXML = null;\n\n /**\n * Method to call when the state changes.\n * @type {?function()}\n */\n this.onreadystatechange = null;\n\n /** @private {!Headers} */\n this.requestHeaders_ = new Headers();\n\n /** @private {?Headers} */\n this.responseHeaders_ = null;\n\n /**\n * Request method (GET or POST).\n * @private {string}\n */\n this.method_ = 'GET';\n\n /**\n * Request URL.\n * @private {string}\n */\n this.url_ = '';\n\n /**\n * Whether the request is in progress.\n * @private {boolean}\n */\n this.inProgress_ = false;\n\n /** @private @final {?goog.log.Logger} */\n this.logger_ = goog.log.getLogger('goog.net.FetchXmlHttp');\n\n /** @private {?Response} */\n this.fetchResponse_ = null;\n\n /** @private {!ReadableStreamDefaultReader|null} */\n this.currentReader_ = null;\n\n /** @private {?TextDecoder} */\n this.textDecoder_ = null;\n};\ngoog.inherits(goog.net.FetchXmlHttp, goog.events.EventTarget);\n\n\n/**\n * State of the requests.\n * @enum {number}\n */\ngoog.net.FetchXmlHttp.RequestState = {\n UNSENT: 0,\n OPENED: 1,\n HEADER_RECEIVED: 2,\n LOADING: 3,\n DONE: 4,\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.open = function(method, url, opt_async) {\n 'use strict';\n goog.asserts.assert(!!opt_async, 'Only async requests are supported.');\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.UNSENT) {\n this.abort();\n throw new Error('Error reopening a connection');\n }\n\n this.method_ = method;\n this.url_ = url;\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.OPENED;\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.send = function(opt_data) {\n 'use strict';\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.OPENED) {\n this.abort();\n throw new Error('need to call open() first. ');\n }\n\n this.inProgress_ = true;\n const requestInit = {\n headers: this.requestHeaders_,\n method: this.method_,\n credentials: this.credentialsMode_,\n cache: this.cacheMode_,\n };\n if (opt_data) {\n requestInit['body'] = opt_data;\n }\n\n (this.worker_ || goog.global)\n .fetch(new Request(this.url_, /** @type {!RequestInit} */ (requestInit)))\n .then(\n this.handleResponse_.bind(this), this.handleSendFailure_.bind(this));\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.abort = function() {\n 'use strict';\n this.response = this.responseText = '';\n this.requestHeaders_ = new Headers();\n this.status = 0;\n\n if (!!this.currentReader_) {\n this.currentReader_.cancel('Request was aborted.')\n .catch(\n e => goog.log.warning(\n this.logger_, 'Fetch reader cancellation error.', e));\n }\n\n if (((this.readyState >= goog.net.FetchXmlHttp.RequestState.OPENED) &&\n this.inProgress_) &&\n (this.readyState != goog.net.FetchXmlHttp.RequestState.DONE)) {\n this.inProgress_ = false;\n this.requestDone_();\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n};\n\n\n/**\n * Handles the fetch response.\n * @param {!Response} response\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponse_ = function(response) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.fetchResponse_ = response;\n\n if (!this.responseHeaders_) {\n this.status = this.fetchResponse_.status;\n this.statusText = this.fetchResponse_.statusText;\n this.responseHeaders_ = response.headers;\n this.readyState = goog.net.FetchXmlHttp.RequestState.HEADER_RECEIVED;\n this.dispatchCallback_();\n }\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.LOADING;\n this.dispatchCallback_();\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.responseType === 'arraybuffer') {\n response.arrayBuffer().then(\n this.handleResponseArrayBuffer_.bind(this),\n this.handleSendFailure_.bind(this));\n } else if (\n typeof (goog.global.ReadableStream) !== 'undefined' &&\n 'body' in response) {\n this.currentReader_ =\n /** @type {!ReadableStreamDefaultReader} */ (response.body.getReader());\n if (this.streamBinaryChunks_) {\n if (this.responseType) {\n throw new Error(\n 'responseType must be empty for \"streamBinaryChunks\" mode responses.');\n }\n this.response = [];\n } else {\n this.response = this.responseText = '';\n this.textDecoder_ = new TextDecoder();\n }\n this.readInputFromFetch_();\n } else {\n response.text().then(\n this.handleResponseText_.bind(this),\n this.handleSendFailure_.bind(this));\n }\n};\n\n\n/**\n * Reads the next chunk of data from the fetch response.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.readInputFromFetch_ = function() {\n 'use strict';\n this.currentReader_.read()\n .then(this.handleDataFromStream_.bind(this))\n .catch(this.handleSendFailure_.bind(this));\n};\n\n\n/**\n * Handles a chunk of data from the fetch response stream reader.\n * @param {!IIterableResult} result\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleDataFromStream_ = function(result) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.streamBinaryChunks_ && result.value) {\n // When streamBinaryChunks_ is enabled, \"response\" is an array\n /** @type {!Array} */ (this.response)\n .push(/** @type {!Uint8Array} */ (result.value));\n } else if (!this.streamBinaryChunks_) {\n const dataPacket = result.value ?\n /** @type {!Uint8Array} */ (result.value) :\n new Uint8Array(0);\n const newText =\n this.textDecoder_.decode(dataPacket, {stream: !result.done});\n if (newText) {\n this.responseText += newText;\n this.response = this.responseText;\n }\n }\n if (result.done) {\n this.requestDone_();\n } else {\n this.dispatchCallback_();\n }\n\n if (this.readyState == goog.net.FetchXmlHttp.RequestState.LOADING) {\n this.readInputFromFetch_();\n }\n};\n\n/**\n * Handles the response text.\n * @param {string} responseText\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseText_ = function(responseText) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = this.responseText = responseText;\n this.requestDone_();\n};\n\n\n/**\n * Handles the response text.\n * @param {!ArrayBuffer} responseArrayBuffer\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_ = function(\n responseArrayBuffer) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = responseArrayBuffer;\n this.requestDone_();\n};\n\n\n/**\n * Handles the send failure.\n * @param {*} error\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleSendFailure_ = function(error) {\n 'use strict';\n const e = error instanceof Error ? error : Error(error);\n goog.log.warning(this.logger_, 'Failed to fetch url ' + this.url_, e);\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.requestDone_();\n};\n\n\n/**\n * Sets the request state to DONE and performs cleanup.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.requestDone_ = function() {\n 'use strict';\n this.readyState = goog.net.FetchXmlHttp.RequestState.DONE;\n\n this.fetchResponse_ = null;\n this.currentReader_ = null;\n this.textDecoder_ = null;\n\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.setRequestHeader = function(header, value) {\n 'use strict';\n this.requestHeaders_.append(header, value);\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getResponseHeader = function(header) {\n 'use strict';\n // TODO(user): This method should return null when the headers are not\n // present or the specified header is missing. The externs need to be fixed.\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get response header but no headers have been received ' +\n 'for url: ' + this.url_);\n return '';\n }\n return this.responseHeaders_.get(header.toLowerCase()) || '';\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getAllResponseHeaders = function() {\n 'use strict';\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get all response headers but no headers have been ' +\n 'received for url: ' + this.url_);\n return '';\n }\n const lines = [];\n const iter = this.responseHeaders_.entries();\n let entry = iter.next();\n while (!entry.done) {\n const pair = entry.value;\n lines.push(pair[0] + ': ' + pair[1]);\n entry = iter.next();\n }\n return lines.join('\\r\\n');\n};\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCredentialsMode = function(credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n/**\n * @return {!RequestCredentials|undefined} The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.getCredentialsMode = function() {\n 'use strict';\n return this.credentialsMode_;\n};\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n/**\n * Dispatches the callback, if the callback attribute is defined.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.dispatchCallback_ = function() {\n 'use strict';\n if (this.onreadystatechange) {\n this.onreadystatechange.call(this);\n }\n};\n\n// Polyfill XmlHttpRequest's withCredentials property for specifying whether to\n// include credentials on cross domain requests.\nObject.defineProperty(goog.net.FetchXmlHttp.prototype, 'withCredentials', {\n get:\n /**\n * @this {goog.net.FetchXmlHttp}\n * @return {boolean} Whether to include credentials in cross domain\n * requests.\n */\n function() {\n 'use strict';\n return this.getCredentialsMode() === 'include';\n },\n\n set:\n /**\n * @param {boolean} value Whether to include credentials in cross domain\n * requests.\n * @this {goog.net.FetchXmlHttp}\n **/\n function(value) {\n 'use strict';\n this.setCredentialsMode(value ? 'include' : 'same-origin');\n }\n});\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Utility to attempt native JSON processing, falling back to\n * goog.json if not available.\n *\n * This is intended as a drop-in for current users of goog.json who want\n * to take advantage of native JSON if present.\n */\n\ngoog.provide('goog.json.hybrid');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json');\n\n\n/**\n * Attempts to serialize the JSON string natively, falling back to\n * `goog.json.serialize` if unsuccessful.\n * @param {!Object} obj JavaScript object to serialize to JSON.\n * @return {string} Resulting JSON string.\n */\ngoog.json.hybrid.stringify = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['stringify'] :\n function(obj) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n return goog.global.JSON.stringify(obj);\n } catch (e) {\n // Native serialization failed. Fall through to retry with\n // goog.json.serialize.\n }\n }\n\n return goog.json.serialize(obj);\n };\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * the supplied `fallbackParser` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\n * if native\n * @return {?Object} Resulting JSON object.\n * @private\n */\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n var obj = goog.global.JSON.parse(jsonString);\n goog.asserts.assert(typeof obj == 'object');\n return /** @type {?Object} */ (obj);\n } catch (e) {\n // Native parse failed. Fall through to retry with goog.json.parse.\n }\n }\n\n return fallbackParser(jsonString);\n};\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * `goog.json.parse` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @return {?Object} Resulting JSON object.\n */\ngoog.json.hybrid.parse = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['parse'] :\n function(jsonString) {\n 'use strict';\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\n };\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Constants for HTTP status codes.\n */\n\ngoog.provide('goog.net.HttpStatus');\n\n\n/**\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n * @see http://tools.ietf.org/html/rfc6585\n * @see https://tools.ietf.org/html/rfc4918\n * @see https://tools.ietf.org/html/rfc7538\n * @enum {number}\n */\ngoog.net.HttpStatus = {\n // Informational 1xx\n CONTINUE: 100,\n SWITCHING_PROTOCOLS: 101,\n\n // Successful 2xx\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NON_AUTHORITATIVE_INFORMATION: 203,\n NO_CONTENT: 204,\n RESET_CONTENT: 205,\n PARTIAL_CONTENT: 206,\n MULTI_STATUS: 207,\n\n // Redirection 3xx\n MULTIPLE_CHOICES: 300,\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n SEE_OTHER: 303,\n NOT_MODIFIED: 304,\n USE_PROXY: 305,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // Client Error 4xx\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n REQUEST_TIMEOUT: 408,\n CONFLICT: 409,\n GONE: 410,\n LENGTH_REQUIRED: 411,\n PRECONDITION_FAILED: 412,\n REQUEST_ENTITY_TOO_LARGE: 413,\n REQUEST_URI_TOO_LONG: 414,\n UNSUPPORTED_MEDIA_TYPE: 415,\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\n EXPECTATION_FAILED: 417,\n UNPROCESSABLE_ENTITY: 422,\n LOCKED: 423,\n FAILED_DEPENDENCY: 424,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n CLIENT_CLOSED_REQUEST: 499, // Nonstandard, used by GRPC\n\n // Server Error 5xx\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n INSUFFICIENT_STORAGE: 507,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n\n /*\n * IE returns this code for 204 due to its use of URLMon, which returns this\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\n */\n QUIRK_IE_NO_CONTENT: 1223,\n};\n\n\n/**\n * Returns whether the given status should be considered successful.\n *\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\n * and IE's no content code (1223).\n *\n * @param {number} status The status code to test.\n * @return {boolean} Whether the status code should be considered successful.\n */\ngoog.net.HttpStatus.isSuccess = function(status) {\n 'use strict';\n switch (status) {\n case goog.net.HttpStatus.OK:\n case goog.net.HttpStatus.CREATED:\n case goog.net.HttpStatus.ACCEPTED:\n case goog.net.HttpStatus.NO_CONTENT:\n case goog.net.HttpStatus.PARTIAL_CONTENT:\n case goog.net.HttpStatus.NOT_MODIFIED:\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\n return true;\n\n default:\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides CORS support for HTTP based RPC requests.\n *\n * As part of net.rpc package, CORS features provided by this class\n * depend on the server support. Please check related specs to decide how\n * to enable any of the features provided by this class.\n */\n\ngoog.module('goog.net.rpc.HttpCors');\n\nconst GoogUri = goog.require('goog.Uri');\nconst googObject = goog.require('goog.object');\nconst googString = goog.require('goog.string');\nconst googUriUtils = goog.require('goog.uri.utils');\n\n\n/**\n * The default URL parameter name to overwrite http headers with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\n\n\n/**\n * The default URL parameter name to overwrite http method with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\n\n\n/**\n * Generates the URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateHttpHeadersOverwriteParam = function(headers) {\n let result = '';\n googObject.forEach(headers, function(value, key) {\n result += key;\n result += ':';\n result += value;\n result += '\\r\\n';\n });\n return result;\n};\n\n\n/**\n * Generates the URL-encoded URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\n return googString.urlEncode(\n exports.generateHttpHeadersOverwriteParam(headers));\n};\n\n\n/**\n * Sets custom HTTP headers via an overwrite URL param.\n *\n * @param {!GoogUri|string} url The URI object or a string path.\n * @param {string} urlParam The URL param name.\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\n * @return {!GoogUri|string} The URI object or a string path with headers\n * encoded as a url param.\n */\nexports.setHttpHeadersWithOverwriteParam = function(\n url, urlParam, extraHeaders) {\n if (googObject.isEmpty(extraHeaders)) {\n return url;\n }\n const httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\n if (typeof url === 'string') {\n return googUriUtils.appendParam(\n url, googString.urlEncode(urlParam), httpHeaders);\n } else {\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\n return url;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\n *\n * When WebChannelBase is used as the underlying transport, the capabilities\n * of the WebChannel are limited to what's supported by the implementation.\n * Particularly, multiplexing is not possible, and only strings are\n * supported as message types.\n */\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.log');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.WebChannelTransport');\ngoog.require('goog.object');\ngoog.require('goog.string');\n\n\n\n/**\n * Implementation of {@link goog.net.WebChannelTransport} with\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\n * implementation.\n *\n * @constructor\n * @struct\n * @implements {goog.net.WebChannelTransport}\n * @final\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\n 'use strict';\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\n throw new Error('Environmental error: no available transport.');\n }\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannelBaseTransport =\n goog.labs.net.webChannel.WebChannelBaseTransport;\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.prototype.createWebChannel = function(\n url, opt_options) {\n 'use strict';\n return new WebChannelBaseTransport.Channel(url, opt_options);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel} interface.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance.\n *\n * @constructor\n * @implements {goog.net.WebChannel}\n * @extends {goog.events.EventTarget}\n * @final\n */\nWebChannelBaseTransport.Channel = function(url, opt_options) {\n 'use strict';\n WebChannelBaseTransport.Channel.base(this, 'constructor');\n\n /**\n * @private {!WebChannelBase} The underlying channel object.\n */\n this.channel_ = new WebChannelBase(\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\n\n /**\n * @private {string} The URL of the target server end-point.\n */\n this.url_ = url;\n\n /**\n * @private {goog.log.Logger} The logger for this class.\n */\n this.logger_ =\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n /**\n * @private {Object<string, string>} Extra URL parameters\n * to be added to each HTTP request.\n */\n this.messageUrlParams_ =\n (opt_options && opt_options.messageUrlParams) || null;\n\n let messageHeaders = (opt_options && opt_options.messageHeaders) || null;\n\n // default is false\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\n if (messageHeaders) {\n goog.object.set(\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n } else {\n messageHeaders = goog.object.create(\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n }\n }\n\n this.channel_.setExtraHeaders(messageHeaders);\n\n let initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\n\n if (opt_options && opt_options.messageContentType) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n }\n }\n\n if (opt_options && opt_options.clientProfile) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n }\n }\n\n this.channel_.setInitHeaders(initHeaders);\n\n const httpHeadersOverwriteParam =\n opt_options && opt_options.httpHeadersOverwriteParam;\n if (httpHeadersOverwriteParam &&\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\n }\n\n /**\n * @private {boolean} Whether to enable CORS.\n */\n this.supportsCrossDomainXhr_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\n */\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\n\n // Note that httpSessionIdParam will be ignored if the same parameter name\n // has already been specified with messageUrlParams\n const httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\n if (httpSessionIdParam &&\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\n goog.log.warning(\n this.logger_,\n 'Ignore httpSessionIdParam also specified with messageUrlParams: ' +\n httpSessionIdParam);\n }\n }\n\n /**\n * The channel handler.\n *\n * @private {!WebChannelBaseTransport.Channel.Handler_}\n */\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\n};\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.open = function() {\n 'use strict';\n this.channel_.setHandler(this.channelHandler_);\n if (this.supportsCrossDomainXhr_) {\n this.channel_.setSupportsCrossDomainXhrs(true);\n }\n this.channel_.connect(this.url_, (this.messageUrlParams_ || undefined));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.close = function() {\n 'use strict';\n this.channel_.disconnect();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\n 'use strict';\n // to be implemented\n throw new Error('Not implemented');\n};\n\n\n/**\n * The WebChannelBase only supports object types.\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n *\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\n 'use strict';\n this.channel_.sendMap(this.messageToMapObject_(message));\n};\n\n\n/**\n * Converts a message to the map used by the underlying channel.\n *\n * @param {!goog.net.WebChannel.MessageData} message\n * @return {!Object|!goog.collections.maps.MapLike}\n */\nWebChannelBaseTransport.Channel.prototype.messageToMapObject_ = function(\n message) {\n 'use strict';\n goog.asserts.assert(\n goog.isObject(message) || typeof message === 'string',\n 'only object type or raw string is supported');\n\n if (typeof message === 'string') {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = message;\n return rawJson;\n }\n\n if (this.sendRawJson_) {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\n return rawJson;\n }\n\n return message;\n};\n\n\n/**\n * Converts the map used by the underlying channel to a message.\n *\n * NOTE: In the case of the message being JS Object or string, the exact same\n * object passed during `messageToMapObject_()` is returned. In the case of raw\n * JSON, an equal (but not the same) object is returned (due to serialization).\n *\n * @param {!Object|!goog.collections.maps.MapLike} map\n * @return {!goog.net.WebChannel.MessageData}\n */\nWebChannelBaseTransport.Channel.prototype.mapObjectToMessage_ = function(map) {\n 'use strict';\n if (Wire.RAW_DATA_KEY in map) {\n const rawMessage = map[Wire.RAW_DATA_KEY];\n\n if (this.sendRawJson_) {\n return /** @type {!goog.net.WebChannel.MessageData} */ (\n goog.json.parse(rawMessage));\n } else { // string message\n return rawMessage;\n }\n }\n\n return map;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\n 'use strict';\n this.channel_.setHandler(null);\n delete this.channelHandler_;\n this.channel_.disconnect();\n delete this.channel_;\n\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\n};\n\n\n\n/**\n * The message event.\n *\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\n * @constructor\n * @extends {goog.net.WebChannel.MessageEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\n 'use strict';\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\n\n // single-metadata only\n const metadata = array['__sm__'];\n if (metadata) {\n this.metadataKey = goog.object.getAnyKey(metadata);\n if (this.metadataKey) {\n this.data = goog.object.get(metadata, this.metadataKey);\n } else {\n this.data = metadata; // empty\n }\n } else {\n this.data = array;\n }\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.MessageEvent,\n goog.net.WebChannel.MessageEvent);\n\n\n\n/**\n * The error event.\n *\n * @param {WebChannelBase.Error} error The error code.\n * @constructor\n * @extends {goog.net.WebChannel.ErrorEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\n 'use strict';\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\n\n /**\n * High-level status code.\n */\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\n\n /**\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\n */\n this.errorCode = error;\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\n\n\n\n/**\n * Implementation of {@link WebChannelBase.Handler} interface.\n *\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\n *\n * @constructor\n * @extends {WebChannelBase.Handler}\n * @private\n */\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\n 'use strict';\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\n\n /**\n * @type {!WebChannelBaseTransport.Channel}\n * @private\n */\n this.channel_ = channel;\n};\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\n channel) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\n function(channel, array) {\n 'use strict';\n goog.asserts.assert(array, 'array expected to be defined');\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.MessageEvent(array));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\n channel, error) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_,\n 'WebChannel aborted on ' + this.channel_.url_ +\n ' due to channel error: ' + error);\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\n 'use strict';\n return new WebChannelBaseTransport.ChannelProperties(this, this.channel_);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\n *\n * @param {!WebChannelBaseTransport.Channel} transportChannel The transport\n * channel object.\n * @param {!WebChannelBase} channel The underlying channel object.\n *\n * @constructor\n * @implements {goog.net.WebChannel.RuntimeProperties}\n * @final\n */\nWebChannelBaseTransport.ChannelProperties = function(\n transportChannel, channel) {\n 'use strict';\n /**\n * The transport channel object.\n *\n * @private @const {!WebChannelBaseTransport.Channel}\n */\n this.transportChannel_ = transportChannel;\n\n /**\n * The underlying channel object.\n *\n * @private @const {!WebChannelBase}\n */\n this.channel_ = channel;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\n 'use strict';\n return this.getConcurrentRequestLimit() > 1;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\n};\n\n\n/**\n * @override\n * @return {!Array<!goog.net.WebChannel.MessageData>}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessages =\n function() {\n 'use strict';\n return this.channel_.getNonAckedMaps().map(\n queued_map => this.transportChannel_.mapObjectToMessage_(queued_map.map));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\n function() {\n 'use strict';\n return this.channel_.getHttpSessionId();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\n callback) {\n 'use strict';\n this.channel_.setForwardChannelFlushCallback(callback);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\n goog.abstractMethod;\n\n\n/** @override */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\n function() {\n 'use strict';\n return this.channel_.getLastStatusCode();\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Transport support for WebChannel.\n *\n * The <code>WebChannelTransport</code> implementation serves as the factory\n * for <code>WebChannel</code>, which offers an abstraction for\n * point-to-point socket-like communication similar to what BrowserChannel\n * or HTML5 WebSocket offers.\n */\n\ngoog.provide('goog.net.WebChannelTransport');\n\ngoog.requireType('goog.net.WebChannel');\ngoog.requireType('goog.net.WebChannel.Options');\n\n\n\n/**\n * A WebChannelTransport instance represents a shared context of logical\n * connectivity between a browser client and a remote origin.\n *\n * Over a single WebChannelTransport instance, multiple WebChannels may be\n * created against different URLs, which may all share the same\n * underlying connectivity (i.e. TCP connection) whenever possible.\n *\n * When multi-domains are supported, such as CORS, multiple origins may be\n * supported over a single WebChannelTransport instance at the same time.\n *\n * Sharing between different window contexts such as tabs is not addressed\n * by WebChannelTransport. Applications may choose HTML5 shared workers\n * or other techniques to access the same transport instance\n * across different window contexts.\n *\n * @interface\n */\ngoog.net.WebChannelTransport = function() {};\n\n\n/**\n * The client version. This integer value will be passed to the server\n * when a channel is opened to inform the server the client \"capabilities\".\n *\n * Wire protocol version is a different concept and is internal to the\n * transport implementation.\n *\n * @const\n * @type {number}\n */\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\n\n\n/**\n * Create a new WebChannel instance.\n *\n * The new WebChannel is to be opened against the server-side resource\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\n * semantics.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance. The configuration object is reusable after\n * the new channel instance is created.\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\n */\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Bring in closure-library dependencies\n */\n\ngoog.provide('firebase.webchannel.wrapper');\n\n// goog.net.WebChannelTransport\ngoog.require('goog.net.createWebChannelTransport');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n/**\n * NOTE: The `createWebChannel` function takes an options object as a second param\n * whose properties are typically mangled. We override these in externs/overrides.js\n * Without those externs, this does not function properly.\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport.prototype['createWebChannel'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.prototype.createWebChannel;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['send'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.send;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['open'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.open;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['close'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.close;\n\n// goog.net.ErrorCode\ngoog.require('goog.net.ErrorCode');\ngoog.net.ErrorCode['NO_ERROR'] = goog.net.ErrorCode.NO_ERROR;\ngoog.net.ErrorCode['TIMEOUT'] = goog.net.ErrorCode.TIMEOUT;\ngoog.net.ErrorCode['HTTP_ERROR'] = goog.net.ErrorCode.HTTP_ERROR;\n\n// goog.net.ErrorType\ngoog.require('goog.net.EventType');\ngoog.net.EventType['COMPLETE'] = goog.net.EventType.COMPLETE;\n\n// goog.net.WebChannel\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.events.EventTarget');\ngoog.net.WebChannel['EventType'] = goog.net.WebChannel.EventType;\ngoog.net.WebChannel.EventType['OPEN'] = goog.net.WebChannel.EventType.OPEN;\ngoog.net.WebChannel.EventType['CLOSE'] = goog.net.WebChannel.EventType.CLOSE;\ngoog.net.WebChannel.EventType['ERROR'] = goog.net.WebChannel.EventType.ERROR;\ngoog.net.WebChannel.EventType['MESSAGE'] =\n goog.net.WebChannel.EventType.MESSAGE;\ngoog.events.EventTarget.prototype['listen'] =\n goog.events.EventTarget.prototype.listen;\n\ngoog.require('goog.net.XhrIo');\ngoog.net.XhrIo.prototype['listenOnce'] = goog.net.XhrIo.prototype.listenOnce;\ngoog.net.XhrIo.prototype['getLastError'] =\n goog.net.XhrIo.prototype.getLastError;\ngoog.net.XhrIo.prototype['getLastErrorCode'] =\n goog.net.XhrIo.prototype.getLastErrorCode;\ngoog.net.XhrIo.prototype['getStatus'] = goog.net.XhrIo.prototype.getStatus;\ngoog.net.XhrIo.prototype['getResponseJson'] =\n goog.net.XhrIo.prototype.getResponseJson;\ngoog.net.XhrIo.prototype['getResponseText'] =\n goog.net.XhrIo.prototype.getResponseText;\ngoog.net.XhrIo.prototype['send'] = goog.net.XhrIo.prototype.send;\ngoog.net.XhrIo.prototype['setWithCredentials'] =\n goog.net.XhrIo.prototype.setWithCredentials;\n\nmodule['exports']['createWebChannelTransport'] =\n goog.net.createWebChannelTransport;\nmodule['exports']['getStatEventTarget'] =\n goog.labs.net.webChannel.requestStats.getStatEventTarget;\nmodule['exports']['ErrorCode'] = goog.net.ErrorCode;\nmodule['exports']['EventType'] = goog.net.EventType;\nmodule['exports']['Event'] = goog.labs.net.webChannel.requestStats.Event;\nmodule['exports']['Stat'] = goog.labs.net.webChannel.requestStats.Stat;\nmodule['exports']['FetchXmlHttpFactory'] = goog.net.FetchXmlHttpFactory;\nmodule['exports']['WebChannel'] = goog.net.WebChannel;\nmodule['exports']['XhrIo'] = goog.net.XhrIo;\n","import { _getProvider, getApp as t, _removeServiceInstance as e, _registerComponent as n, registerVersion as s, SDK_VERSION as i } from \"@firebase/app\";\n\nimport { Component as r } from \"@firebase/component\";\n\nimport { Logger as o, LogLevel as u } from \"@firebase/logger\";\n\nimport { FirebaseError as c, getUA as a, isIndexedDBAvailable as h, isSafari as l, createMockUserToken as f, getModularInstance as d, deepEqual as _, getDefaultEmulatorHostnameAndPort as w } from \"@firebase/util\";\n\nimport { XhrIo as m, EventType as g, ErrorCode as y, createWebChannelTransport as p, getStatEventTarget as I, FetchXmlHttpFactory as T, WebChannel as E, Event as A, Stat as R } from \"@firebase/webchannel-wrapper\";\n\nconst b = \"@firebase/firestore\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nclass P {\n constructor(t) {\n this.uid = t;\n }\n isAuthenticated() {\n return null != this.uid;\n }\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */ toKey() {\n return this.isAuthenticated() ? \"uid:\" + this.uid : \"anonymous-user\";\n }\n isEqual(t) {\n return t.uid === this.uid;\n }\n}\n\n/** A user with a null UID. */ P.UNAUTHENTICATED = new P(null), \n// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nP.GOOGLE_CREDENTIALS = new P(\"google-credentials-uid\"), P.FIRST_PARTY = new P(\"first-party-uid\"), \nP.MOCK_USER = new P(\"mock-user\");\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet v = \"9.16.0\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst V = new o(\"@firebase/firestore\");\n\n// Helper methods are needed because variables can't be exported as read/write\nfunction S() {\n return V.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * <ul>\n * <li>`debug` for the most verbose logging level, primarily for\n * debugging.</li>\n * <li>`error` to log errors only.</li>\n * <li><code>`silent` to turn off logging.</li>\n * </ul>\n */ function D(t) {\n V.setLogLevel(t);\n}\n\nfunction C(t, ...e) {\n if (V.logLevel <= u.DEBUG) {\n const n = e.map(k);\n V.debug(`Firestore (${v}): ${t}`, ...n);\n }\n}\n\nfunction x(t, ...e) {\n if (V.logLevel <= u.ERROR) {\n const n = e.map(k);\n V.error(`Firestore (${v}): ${t}`, ...n);\n }\n}\n\n/**\n * @internal\n */ function N(t, ...e) {\n if (V.logLevel <= u.WARN) {\n const n = e.map(k);\n V.warn(`Firestore (${v}): ${t}`, ...n);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function k(t) {\n if (\"string\" == typeof t) return t;\n try {\n return e = t, JSON.stringify(e);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return t;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /** Formats an object as a JSON string, suitable for logging. */\n var e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function O(t = \"Unexpected state\") {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const e = `FIRESTORE (${v}) INTERNAL ASSERTION FAILED: ` + t;\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw x(e), new Error(e);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function M(t, e) {\n t || O();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function F(t, e) {\n t || O();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function $(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n return t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const B = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: \"ok\",\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: \"cancelled\",\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: \"unknown\",\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: \"invalid-argument\",\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: \"deadline-exceeded\",\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: \"not-found\",\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: \"already-exists\",\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: \"permission-denied\",\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: \"unauthenticated\",\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: \"resource-exhausted\",\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: \"failed-precondition\",\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: \"aborted\",\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: \"out-of-range\",\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: \"unimplemented\",\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: \"internal\",\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: \"unavailable\",\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class L extends c {\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n t, \n /**\n * A custom error description.\n */\n e) {\n super(t, e), this.code = t, this.message = e, \n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class q {\n constructor() {\n this.promise = new Promise(((t, e) => {\n this.resolve = t, this.reject = e;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class U {\n constructor(t, e) {\n this.user = e, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${t}`);\n }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class K {\n getToken() {\n return Promise.resolve(null);\n }\n invalidateToken() {}\n start(t, e) {\n // Fire with initial user.\n t.enqueueRetryable((() => e(P.UNAUTHENTICATED)));\n }\n shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class G {\n constructor(t) {\n this.token = t, \n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.changeListener = null;\n }\n getToken() {\n return Promise.resolve(this.token);\n }\n invalidateToken() {}\n start(t, e) {\n this.changeListener = e, \n // Fire with initial user.\n t.enqueueRetryable((() => e(this.token.user)));\n }\n shutdown() {\n this.changeListener = null;\n }\n}\n\nclass Q {\n constructor(t) {\n this.t = t, \n /** Tracks the current User. */\n this.currentUser = P.UNAUTHENTICATED, \n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n this.i = 0, this.forceRefresh = !1, this.auth = null;\n }\n start(t, e) {\n let n = this.i;\n // A change listener that prevents double-firing for the same token change.\n const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let i = new q;\n this.o = () => {\n this.i++, this.currentUser = this.u(), i.resolve(), i = new q, t.enqueueRetryable((() => s(this.currentUser)));\n };\n const r = () => {\n const e = i;\n t.enqueueRetryable((async () => {\n await e.promise, await s(this.currentUser);\n }));\n }, o = t => {\n C(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = t, this.auth.addAuthTokenListener(this.o), \n r();\n };\n this.t.onInit((t => o(t))), \n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout((() => {\n if (!this.auth) {\n const t = this.t.getImmediate({\n optional: !0\n });\n t ? o(t) : (\n // If auth is still not available, proceed with `null` user\n C(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), i.resolve(), i = new q);\n }\n }), 0), r();\n }\n getToken() {\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const t = this.i, e = this.forceRefresh;\n return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e => \n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n this.i !== t ? (C(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n this.getToken()) : e ? (M(\"string\" == typeof e.accessToken), new U(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.auth && this.auth.removeAuthTokenListener(this.o);\n }\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n u() {\n const t = this.auth && this.auth.getUid();\n return M(null === t || \"string\" == typeof t), new P(t);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class j {\n constructor(t, e, n, s) {\n this.h = t, this.l = e, this.m = n, this.g = s, this.type = \"FirstParty\", this.user = P.FIRST_PARTY, \n this.p = new Map;\n }\n /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */ I() {\n return this.g ? this.g() : (\n // Make sure this really is a Gapi client.\n M(!(\"object\" != typeof this.h || null === this.h || !this.h.auth || !this.h.auth.getAuthHeaderValueForFirstParty)), \n this.h.auth.getAuthHeaderValueForFirstParty([]));\n }\n get headers() {\n this.p.set(\"X-Goog-AuthUser\", this.l);\n // Use array notation to prevent minification\n const t = this.I();\n return t && this.p.set(\"Authorization\", t), this.m && this.p.set(\"X-Goog-Iam-Authorization-Token\", this.m), \n this.p;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class W {\n constructor(t, e, n, s) {\n this.h = t, this.l = e, this.m = n, this.g = s;\n }\n getToken() {\n return Promise.resolve(new j(this.h, this.l, this.m, this.g));\n }\n start(t, e) {\n // Fire with initial uid.\n t.enqueueRetryable((() => e(P.FIRST_PARTY)));\n }\n shutdown() {}\n invalidateToken() {}\n}\n\nclass z {\n constructor(t) {\n this.value = t, this.type = \"AppCheck\", this.headers = new Map, t && t.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n }\n}\n\nclass H {\n constructor(t) {\n this.T = t, this.forceRefresh = !1, this.appCheck = null, this.A = null;\n }\n start(t, e) {\n const n = t => {\n null != t.error && C(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);\n const n = t.token !== this.A;\n return this.A = t.token, C(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n n ? e(t.token) : Promise.resolve();\n };\n this.o = e => {\n t.enqueueRetryable((() => n(e)));\n };\n const s = t => {\n C(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = t, this.appCheck.addTokenListener(this.o);\n };\n this.T.onInit((t => s(t))), \n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout((() => {\n if (!this.appCheck) {\n const t = this.T.getImmediate({\n optional: !0\n });\n t ? s(t) : \n // If AppCheck is still not available, proceed without it.\n C(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n }\n }), 0);\n }\n getToken() {\n const t = this.forceRefresh;\n return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (M(\"string\" == typeof t.token), \n this.A = t.token, new z(t.token)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.appCheck && this.appCheck.removeTokenListener(this.o);\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class J {\n getToken() {\n return Promise.resolve(new z(\"\"));\n }\n invalidateToken() {}\n start(t, e) {}\n shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction Y(t) {\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const e = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);\n if (e && \"function\" == typeof e.getRandomValues) e.getRandomValues(n); else \n // Falls back to Math.random\n for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());\n return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class X {\n static R() {\n // Alphanumeric characters\n const t = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", e = Math.floor(256 / t.length) * t.length;\n // The largest byte value that is a multiple of `char.length`.\n let n = \"\";\n for (;n.length < 20; ) {\n const s = Y(40);\n for (let i = 0; i < s.length; ++i) \n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));\n }\n return n;\n }\n}\n\nfunction Z(t, e) {\n return t < e ? -1 : t > e ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function tt(t, e, n) {\n return t.length === e.length && t.every(((t, s) => n(t, e[s])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function et(t) {\n // Return the input string, with an additional NUL byte appended.\n return t + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass nt {\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n t, \n /**\n * The fractions of a second at nanosecond resolution.*\n */\n e) {\n if (this.seconds = t, this.nanoseconds = e, e < 0) throw new L(B.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (e >= 1e9) throw new L(B.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (t < -62135596800) throw new L(B.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n // This will break in the year 10,000.\n if (t >= 253402300800) throw new L(B.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n }\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */ static now() {\n return nt.fromMillis(Date.now());\n }\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */ static fromDate(t) {\n return nt.fromMillis(t.getTime());\n }\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */ static fromMillis(t) {\n const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));\n return new nt(e, n);\n }\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */ toDate() {\n return new Date(this.toMillis());\n }\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */ toMillis() {\n return 1e3 * this.seconds + this.nanoseconds / 1e6;\n }\n _compareTo(t) {\n return this.seconds === t.seconds ? Z(this.nanoseconds, t.nanoseconds) : Z(this.seconds, t.seconds);\n }\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */ isEqual(t) {\n return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;\n }\n /** Returns a textual representation of this `Timestamp`. */ toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }\n /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */ valueOf() {\n // This method returns a string of the form <seconds>.<nanoseconds> where\n // <seconds> is translated to have a non-negative value and both <seconds>\n // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The <seconds> translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const t = this.seconds - -62135596800;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n return String(t).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class st {\n constructor(t) {\n this.timestamp = t;\n }\n static fromTimestamp(t) {\n return new st(t);\n }\n static min() {\n return new st(new nt(0, 0));\n }\n static max() {\n return new st(new nt(253402300799, 999999999));\n }\n compareTo(t) {\n return this.timestamp._compareTo(t.timestamp);\n }\n isEqual(t) {\n return this.timestamp.isEqual(t.timestamp);\n }\n /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {\n // Convert to microseconds.\n return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n }\n toString() {\n return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n }\n toTimestamp() {\n return this.timestamp;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass it {\n constructor(t, e, n) {\n void 0 === e ? e = 0 : e > t.length && O(), void 0 === n ? n = t.length - e : n > t.length - e && O(), \n this.segments = t, this.offset = e, this.len = n;\n }\n get length() {\n return this.len;\n }\n isEqual(t) {\n return 0 === it.comparator(this, t);\n }\n child(t) {\n const e = this.segments.slice(this.offset, this.limit());\n return t instanceof it ? t.forEach((t => {\n e.push(t);\n })) : e.push(t), this.construct(e);\n }\n /** The index of one past the last segment of the path. */ limit() {\n return this.offset + this.length;\n }\n popFirst(t) {\n return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);\n }\n popLast() {\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n firstSegment() {\n return this.segments[this.offset];\n }\n lastSegment() {\n return this.get(this.length - 1);\n }\n get(t) {\n return this.segments[this.offset + t];\n }\n isEmpty() {\n return 0 === this.length;\n }\n isPrefixOf(t) {\n if (t.length < this.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n isImmediateParentOf(t) {\n if (this.length + 1 !== t.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n forEach(t) {\n for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);\n }\n toArray() {\n return this.segments.slice(this.offset, this.limit());\n }\n static comparator(t, e) {\n const n = Math.min(t.length, e.length);\n for (let s = 0; s < n; s++) {\n const n = t.get(s), i = e.get(s);\n if (n < i) return -1;\n if (n > i) return 1;\n }\n return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class rt extends it {\n construct(t, e, n) {\n return new rt(t, e, n);\n }\n canonicalString() {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join(\"/\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */ static fromString(...t) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n const e = [];\n for (const n of t) {\n if (n.indexOf(\"//\") >= 0) throw new L(B.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n // Strip leading and traling slashed.\n e.push(...n.split(\"/\").filter((t => t.length > 0)));\n }\n return new rt(e);\n }\n static emptyPath() {\n return new rt([]);\n }\n}\n\nconst ot = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class ut extends it {\n construct(t, e, n) {\n return new ut(t, e, n);\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */ static isValidIdentifier(t) {\n return ot.test(t);\n }\n canonicalString() {\n return this.toArray().map((t => (t = t.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n ut.isValidIdentifier(t) || (t = \"`\" + t + \"`\"), t))).join(\".\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns true if this field references the key of a document.\n */ isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }\n /**\n * The field designating the key of a document.\n */ static keyField() {\n return new ut([ \"__name__\" ]);\n }\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */ static fromServerFormat(t) {\n const e = [];\n let n = \"\", s = 0;\n const i = () => {\n if (0 === n.length) throw new L(B.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n e.push(n), n = \"\";\n };\n let r = !1;\n for (;s < t.length; ) {\n const e = t[s];\n if (\"\\\\\" === e) {\n if (s + 1 === t.length) throw new L(B.INVALID_ARGUMENT, \"Path has trailing escape character: \" + t);\n const e = t[s + 1];\n if (\"\\\\\" !== e && \".\" !== e && \"`\" !== e) throw new L(B.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + t);\n n += e, s += 2;\n } else \"`\" === e ? (r = !r, s++) : \".\" !== e || r ? (n += e, s++) : (i(), s++);\n }\n if (i(), r) throw new L(B.INVALID_ARGUMENT, \"Unterminated ` in path: \" + t);\n return new ut(e);\n }\n static emptyPath() {\n return new ut([]);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class ct {\n constructor(t) {\n this.path = t;\n }\n static fromPath(t) {\n return new ct(rt.fromString(t));\n }\n static fromName(t) {\n return new ct(rt.fromString(t).popFirst(5));\n }\n static empty() {\n return new ct(rt.emptyPath());\n }\n get collectionGroup() {\n return this.path.popLast().lastSegment();\n }\n /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {\n return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;\n }\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {\n return this.path.get(this.path.length - 2);\n }\n /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {\n return this.path.popLast();\n }\n isEqual(t) {\n return null !== t && 0 === rt.comparator(this.path, t.path);\n }\n toString() {\n return this.path.toString();\n }\n static comparator(t, e) {\n return rt.comparator(t.path, e.path);\n }\n static isDocumentKey(t) {\n return t.length % 2 == 0;\n }\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */ static fromSegments(t) {\n return new ct(new rt(t.slice()));\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass at {\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n t, \n /** The collection ID this index applies to. */\n e, \n /** The field segments for this index. */\n n, \n /** Shows how up-to-date the index is for the current user. */\n s) {\n this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;\n }\n}\n\n/** An ID for an index that has not yet been added to persistence. */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction ht(t) {\n return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function lt(t) {\n return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nfunction ft(t, e) {\n let n = Z(t.collectionGroup, e.collectionGroup);\n if (0 !== n) return n;\n for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = _t(t.fields[s], e.fields[s]), \n 0 !== n) return n;\n return Z(t.fields.length, e.fields.length);\n}\n\n/** Returns a debug representation of the field index */ at.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type. */\nclass dt {\n constructor(\n /** The field path of the component. */\n t, \n /** The fields sorting order. */\n e) {\n this.fieldPath = t, this.kind = e;\n }\n}\n\nfunction _t(t, e) {\n const n = ut.comparator(t.fieldPath, e.fieldPath);\n return 0 !== n ? n : Z(t.kind, e.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class wt {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n t, \n /** The the latest indexed read time, document and batch id. */\n e) {\n this.sequenceNumber = t, this.offset = e;\n }\n /** The state of an index that has not yet been backfilled. */ static empty() {\n return new wt(0, yt.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function mt(t, e) {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = st.fromTimestamp(1e9 === s ? new nt(n + 1, 0) : new nt(n, s));\n return new yt(i, ct.empty(), e);\n}\n\n/** Creates a new offset based on the provided document. */ function gt(t) {\n return new yt(t.readTime, t.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class yt {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n t, \n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n e, \n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n n) {\n this.readTime = t, this.documentKey = e, this.largestBatchId = n;\n }\n /** Returns an offset that sorts before all regular offsets. */ static min() {\n return new yt(st.min(), ct.empty(), -1);\n }\n /** Returns an offset that sorts after all regular offsets. */ static max() {\n return new yt(st.max(), ct.empty(), -1);\n }\n}\n\nfunction pt(t, e) {\n let n = t.readTime.compareTo(e.readTime);\n return 0 !== n ? n : (n = ct.comparator(t.documentKey, e.documentKey), 0 !== n ? n : Z(t.largestBatchId, e.largestBatchId));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const It = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class Tt {\n constructor() {\n this.onCommittedListeners = [];\n }\n addOnCommittedListener(t) {\n this.onCommittedListeners.push(t);\n }\n raiseOnCommittedEvent() {\n this.onCommittedListeners.forEach((t => t()));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function Et(t) {\n if (t.code !== B.FAILED_PRECONDITION || t.message !== It) throw t;\n C(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class At {\n constructor(t) {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n this.nextCallback = null, this.catchCallback = null, \n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = void 0, this.error = void 0, this.isDone = !1, \n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = !1, t((t => {\n this.isDone = !0, this.result = t, this.nextCallback && \n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(t);\n }), (t => {\n this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);\n }));\n }\n catch(t) {\n return this.next(void 0, t);\n }\n next(t, e) {\n return this.callbackAttached && O(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new At(((n, s) => {\n this.nextCallback = e => {\n this.wrapSuccess(t, e).next(n, s);\n }, this.catchCallback = t => {\n this.wrapFailure(e, t).next(n, s);\n };\n }));\n }\n toPromise() {\n return new Promise(((t, e) => {\n this.next(t, e);\n }));\n }\n wrapUserFunction(t) {\n try {\n const e = t();\n return e instanceof At ? e : At.resolve(e);\n } catch (t) {\n return At.reject(t);\n }\n }\n wrapSuccess(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : At.resolve(e);\n }\n wrapFailure(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : At.reject(e);\n }\n static resolve(t) {\n return new At(((e, n) => {\n e(t);\n }));\n }\n static reject(t) {\n return new At(((e, n) => {\n n(t);\n }));\n }\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t) {\n return new At(((e, n) => {\n let s = 0, i = 0, r = !1;\n t.forEach((t => {\n ++s, t.next((() => {\n ++i, r && i === s && e();\n }), (t => n(t)));\n })), r = !0, i === s && e();\n }));\n }\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */ static or(t) {\n let e = At.resolve(!1);\n for (const n of t) e = e.next((t => t ? At.resolve(t) : n()));\n return e;\n }\n static forEach(t, e) {\n const n = [];\n return t.forEach(((t, s) => {\n n.push(e.call(this, t, s));\n })), this.waitFor(n);\n }\n /**\n * Concurrently map all array elements through asynchronous function.\n */ static mapArray(t, e) {\n return new At(((n, s) => {\n const i = t.length, r = new Array(i);\n let o = 0;\n for (let u = 0; u < i; u++) {\n const c = u;\n e(t[c]).next((t => {\n r[c] = t, ++o, o === i && n(r);\n }), (t => s(t)));\n }\n }));\n }\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */ static doWhile(t, e) {\n return new At(((n, s) => {\n const i = () => {\n !0 === t() ? e().next((() => {\n i();\n }), s) : n();\n };\n i();\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass Rt {\n constructor(t, e) {\n this.action = t, this.transaction = e, this.aborted = !1, \n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n this.P = new q, this.transaction.oncomplete = () => {\n this.P.resolve();\n }, this.transaction.onabort = () => {\n e.error ? this.P.reject(new vt(t, e.error)) : this.P.resolve();\n }, this.transaction.onerror = e => {\n const n = xt(e.target.error);\n this.P.reject(new vt(t, n));\n };\n }\n static open(t, e, n, s) {\n try {\n return new Rt(e, t.transaction(s, n));\n } catch (t) {\n throw new vt(e, t);\n }\n }\n get v() {\n return this.P.promise;\n }\n abort(t) {\n t && this.P.reject(t), this.aborted || (C(\"SimpleDb\", \"Aborting transaction:\", t ? t.message : \"Client-initiated abort\"), \n this.aborted = !0, this.transaction.abort());\n }\n V() {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const t = this.transaction;\n this.aborted || \"function\" != typeof t.commit || t.commit();\n }\n /**\n * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */ store(t) {\n const e = this.transaction.objectStore(t);\n return new St(e);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class bt {\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(t, e, n) {\n this.name = t, this.version = e, this.S = n;\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n 12.2 === bt.D(a()) && x(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n }\n /** Deletes the specified database. */ static delete(t) {\n return C(\"SimpleDb\", \"Removing database:\", t), Dt(window.indexedDB.deleteDatabase(t)).toPromise();\n }\n /** Returns true if IndexedDB is available in the current environment. */ static C() {\n if (!h()) return !1;\n if (bt.N()) return !0;\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n const t = a(), e = bt.D(t), n = 0 < e && e < 10, s = bt.k(t), i = 0 < s && s < 4.5;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n // iOS Safari: Disable for users running iOS version < 10.\n return !(t.indexOf(\"MSIE \") > 0 || t.indexOf(\"Trident/\") > 0 || t.indexOf(\"Edge/\") > 0 || n || i);\n }\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */ static N() {\n var t;\n return \"undefined\" != typeof process && \"YES\" === (null === (t = process.env) || void 0 === t ? void 0 : t.O);\n }\n /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {\n return t.store(e);\n }\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static D(t) {\n const e = t.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = e ? e[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static k(t) {\n const e = t.match(/Android ([\\d.]+)/i), n = e ? e[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */ async F(t) {\n return this.db || (C(\"SimpleDb\", \"Opening database:\", this.name), this.db = await new Promise(((e, n) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const s = indexedDB.open(this.name, this.version);\n s.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, s.onblocked = () => {\n n(new vt(t, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n }, s.onerror = e => {\n const s = e.target.error;\n \"VersionError\" === s.name ? n(new L(B.FAILED_PRECONDITION, \"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.\")) : \"InvalidStateError\" === s.name ? n(new L(B.FAILED_PRECONDITION, \"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: \" + s)) : n(new vt(t, s));\n }, s.onupgradeneeded = t => {\n C(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', t.oldVersion);\n const e = t.target.result;\n this.S.$(e, s.transaction, t.oldVersion, this.version).next((() => {\n C(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n }));\n };\n }))), this.B && (this.db.onversionchange = t => this.B(t)), this.db;\n }\n L(t) {\n this.B = t, this.db && (this.db.onversionchange = e => t(e));\n }\n async runTransaction(t, e, n, s) {\n const i = \"readonly\" === e;\n let r = 0;\n for (;;) {\n ++r;\n try {\n this.db = await this.F(t);\n const e = Rt.open(this.db, t, i ? \"readonly\" : \"readwrite\", n), r = s(e).next((t => (e.V(), \n t))).catch((t => (\n // Abort the transaction if there was an error.\n e.abort(t), At.reject(t)))).toPromise();\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n return r.catch((() => {})), \n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await e.v, r;\n } catch (t) {\n const e = t, n = \"FirebaseError\" !== e.name && r < 3;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n if (C(\"SimpleDb\", \"Transaction failed with error:\", e.message, \"Retrying:\", n), \n this.close(), !n) return Promise.reject(e);\n }\n }\n }\n close() {\n this.db && this.db.close(), this.db = void 0;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class Pt {\n constructor(t) {\n this.q = t, this.U = !1, this.K = null;\n }\n get isDone() {\n return this.U;\n }\n get G() {\n return this.K;\n }\n set cursor(t) {\n this.q = t;\n }\n /**\n * This function can be called to stop iteration at any point.\n */ done() {\n this.U = !0;\n }\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */ j(t) {\n this.K = t;\n }\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */ delete() {\n return Dt(this.q.delete());\n }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class vt extends L {\n constructor(t, e) {\n super(B.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = \"IndexedDbTransactionError\";\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function Vt(t) {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return \"IndexedDbTransactionError\" === t.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class St {\n constructor(t) {\n this.store = t;\n }\n put(t, e) {\n let n;\n return void 0 !== e ? (C(\"SimpleDb\", \"PUT\", this.store.name, t, e), n = this.store.put(e, t)) : (C(\"SimpleDb\", \"PUT\", this.store.name, \"<auto-key>\", t), \n n = this.store.put(t)), Dt(n);\n }\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */ add(t) {\n C(\"SimpleDb\", \"ADD\", this.store.name, t, t);\n return Dt(this.store.add(t));\n }\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */ get(t) {\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return Dt(this.store.get(t)).next((e => (\n // Normalize nonexistence to null.\n void 0 === e && (e = null), C(\"SimpleDb\", \"GET\", this.store.name, t, e), e)));\n }\n delete(t) {\n C(\"SimpleDb\", \"DELETE\", this.store.name, t);\n return Dt(this.store.delete(t));\n }\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */ count() {\n C(\"SimpleDb\", \"COUNT\", this.store.name);\n return Dt(this.store.count());\n }\n W(t, e) {\n const n = this.options(t, e);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster. Unfortunately, getAll() does not support custom indices.\n if (n.index || \"function\" != typeof this.store.getAll) {\n const t = this.cursor(n), e = [];\n return this.H(t, ((t, n) => {\n e.push(n);\n })).next((() => e));\n }\n {\n const t = this.store.getAll(n.range);\n return new At(((e, n) => {\n t.onerror = t => {\n n(t.target.error);\n }, t.onsuccess = t => {\n e(t.target.result);\n };\n }));\n }\n }\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */ J(t, e) {\n const n = this.store.getAll(t, null === e ? void 0 : e);\n return new At(((t, e) => {\n n.onerror = t => {\n e(t.target.error);\n }, n.onsuccess = e => {\n t(e.target.result);\n };\n }));\n }\n Y(t, e) {\n C(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n const n = this.options(t, e);\n n.X = !1;\n const s = this.cursor(n);\n return this.H(s, ((t, e, n) => n.delete()));\n }\n Z(t, e) {\n let n;\n e ? n = t : (n = {}, e = t);\n const s = this.cursor(n);\n return this.H(s, e);\n }\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */ tt(t) {\n const e = this.cursor({});\n return new At(((n, s) => {\n e.onerror = t => {\n const e = xt(t.target.error);\n s(e);\n }, e.onsuccess = e => {\n const s = e.target.result;\n s ? t(s.primaryKey, s.value).next((t => {\n t ? s.continue() : n();\n })) : n();\n };\n }));\n }\n H(t, e) {\n const n = [];\n return new At(((s, i) => {\n t.onerror = t => {\n i(t.target.error);\n }, t.onsuccess = t => {\n const i = t.target.result;\n if (!i) return void s();\n const r = new Pt(i), o = e(i.primaryKey, i.value, r);\n if (o instanceof At) {\n const t = o.catch((t => (r.done(), At.reject(t))));\n n.push(t);\n }\n r.isDone ? s() : null === r.G ? i.continue() : i.continue(r.G);\n };\n })).next((() => At.waitFor(n)));\n }\n options(t, e) {\n let n;\n return void 0 !== t && (\"string\" == typeof t ? n = t : e = t), {\n index: n,\n range: e\n };\n }\n cursor(t) {\n let e = \"next\";\n if (t.reverse && (e = \"prev\"), t.index) {\n const n = this.store.index(t.index);\n return t.X ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);\n }\n return this.store.openCursor(t.range, e);\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function Dt(t) {\n return new At(((e, n) => {\n t.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, t.onerror = t => {\n const e = xt(t.target.error);\n n(e);\n };\n }));\n}\n\n// Guard so we only report the error once.\nlet Ct = !1;\n\nfunction xt(t) {\n const e = bt.D(a());\n if (e >= 12.2 && e < 13) {\n const e = \"An internal error was encountered in the Indexed Database server\";\n if (t.message.indexOf(e) >= 0) {\n // Wrap error in a more descriptive one.\n const t = new L(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n return Ct || (Ct = !0, \n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout((() => {\n throw t;\n }), 0)), t;\n }\n }\n return t;\n}\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nclass Nt {\n constructor(t, e) {\n this.asyncQueue = t, this.et = e, this.task = null;\n }\n start() {\n this.nt(15e3);\n }\n stop() {\n this.task && (this.task.cancel(), this.task = null);\n }\n get started() {\n return null !== this.task;\n }\n nt(t) {\n C(\"IndexBackiller\", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay(\"index_backfill\" /* TimerId.IndexBackfill */ , t, (async () => {\n this.task = null;\n try {\n C(\"IndexBackiller\", `Documents written: ${await this.et.st()}`);\n } catch (t) {\n Vt(t) ? C(\"IndexBackiller\", \"Ignoring IndexedDB error during index backfill: \", t) : await Et(t);\n }\n await this.nt(6e4);\n }));\n }\n}\n\n/** Implements the steps for backfilling indexes. */ class kt {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n t, e) {\n this.localStore = t, this.persistence = e;\n }\n async st(t = 50) {\n return this.persistence.runTransaction(\"Backfill Indexes\", \"readwrite-primary\", (e => this.it(e, t)));\n }\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */ it(t, e) {\n const n = new Set;\n let s = e, i = !0;\n return At.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {\n if (null !== e && !n.has(e)) return C(\"IndexBackiller\", `Processing collection: ${e}`), \n this.rt(t, e, s).next((t => {\n s -= t, n.add(e);\n }));\n i = !1;\n })))).next((() => e - s));\n }\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */ rt(t, e, n) {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {\n const i = n.changes;\n return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.ot(s, n))).next((n => (C(\"IndexBackiller\", `Updating offset: ${n}`), \n this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));\n }))));\n }\n /** Returns the next offset based on the provided documents. */ ot(t, e) {\n let n = t;\n return e.changes.forEach(((t, e) => {\n const s = gt(e);\n pt(s, n) > 0 && (n = s);\n })), new yt(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));\n }\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */ class Ot {\n constructor(t, e) {\n this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ut(t), this.ct = t => e.writeSequenceNumber(t));\n }\n ut(t) {\n return this.previousValue = Math.max(t, this.previousValue), this.previousValue;\n }\n next() {\n const t = ++this.previousValue;\n return this.ct && this.ct(t), t;\n }\n}\n\nOt.at = -1;\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Mt {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(t, e, n, s, i, r, o, u) {\n this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i, \n this.forceLongPolling = r, this.autoDetectLongPolling = o, this.useFetchStreams = u;\n }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass Ft {\n constructor(t, e) {\n this.projectId = t, this.database = e || \"(default)\";\n }\n static empty() {\n return new Ft(\"\", \"\");\n }\n get isDefaultDatabase() {\n return \"(default)\" === this.database;\n }\n isEqual(t) {\n return t instanceof Ft && t.projectId === this.projectId && t.database === this.database;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction $t(t) {\n let e = 0;\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;\n return e;\n}\n\nfunction Bt(t, e) {\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);\n}\n\nfunction Lt(t) {\n for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Sentinel value that sorts before any Mutation Batch ID. */\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction qt(t) {\n return null == t;\n}\n\n/** Returns whether the value represents -0. */ function Ut(t) {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return 0 === t && 1 / t == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function Kt(t) {\n return \"number\" == typeof t && Number.isInteger(t) && !Ut(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction Gt() {\n return \"undefined\" != typeof atob;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class Qt {\n constructor(t) {\n this.binaryString = t;\n }\n static fromBase64String(t) {\n const e = atob(t);\n return new Qt(e);\n }\n static fromUint8Array(t) {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const e = \n /**\n * Helper function to convert an Uint8array to a binary string.\n */\n function(t) {\n let e = \"\";\n for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);\n return e;\n }\n /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (t);\n return new Qt(e);\n }\n [Symbol.iterator]() {\n let t = 0;\n return {\n next: () => t < this.binaryString.length ? {\n value: this.binaryString.charCodeAt(t++),\n done: !1\n } : {\n value: void 0,\n done: !0\n }\n };\n }\n toBase64() {\n return t = this.binaryString, btoa(t);\n /** Converts a binary string to a Base64 encoded string. */\n var t;\n }\n toUint8Array() {\n return function(t) {\n const e = new Uint8Array(t.length);\n for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);\n return e;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n (this.binaryString);\n }\n approximateByteSize() {\n return 2 * this.binaryString.length;\n }\n compareTo(t) {\n return Z(this.binaryString, t.binaryString);\n }\n isEqual(t) {\n return this.binaryString === t.binaryString;\n }\n}\n\nQt.EMPTY_BYTE_STRING = new Qt(\"\");\n\nconst jt = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function Wt(t) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (M(!!t), \"string\" == typeof t) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n let e = 0;\n const n = jt.exec(t);\n if (M(!!n), n[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let t = n[1];\n t = (t + \"000000000\").substr(0, 9), e = Number(t);\n }\n // Parse the date to get the seconds.\n const s = new Date(t);\n return {\n seconds: Math.floor(s.getTime() / 1e3),\n nanos: e\n };\n }\n return {\n seconds: zt(t.seconds),\n nanos: zt(t.nanos)\n };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function zt(t) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n return \"number\" == typeof t ? t : \"string\" == typeof t ? Number(t) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function Ht(t) {\n return \"string\" == typeof t ? Qt.fromBase64String(t) : Qt.fromUint8Array(t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */ function Jt(t) {\n var e, n;\n return \"server_timestamp\" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction Yt(t) {\n const e = t.mapValue.fields.__previous_value__;\n return Jt(e) ? Yt(e) : e;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function Xt(t) {\n const e = Wt(t.mapValue.fields.__local_write_time__.timestampValue);\n return new nt(e.seconds, e.nanos);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Zt = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__max__\"\n }\n }\n }\n}, te = {\n nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction ee(t) {\n return \"nullValue\" in t ? 0 /* TypeOrder.NullValue */ : \"booleanValue\" in t ? 1 /* TypeOrder.BooleanValue */ : \"integerValue\" in t || \"doubleValue\" in t ? 2 /* TypeOrder.NumberValue */ : \"timestampValue\" in t ? 3 /* TypeOrder.TimestampValue */ : \"stringValue\" in t ? 5 /* TypeOrder.StringValue */ : \"bytesValue\" in t ? 6 /* TypeOrder.BlobValue */ : \"referenceValue\" in t ? 7 /* TypeOrder.RefValue */ : \"geoPointValue\" in t ? 8 /* TypeOrder.GeoPointValue */ : \"arrayValue\" in t ? 9 /* TypeOrder.ArrayValue */ : \"mapValue\" in t ? Jt(t) ? 4 /* TypeOrder.ServerTimestampValue */ : we(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : O();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function ne(t, e) {\n if (t === e) return !0;\n const n = ee(t);\n if (n !== ee(e)) return !1;\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return !0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return t.booleanValue === e.booleanValue;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return Xt(t).isEqual(Xt(e));\n\n case 3 /* TypeOrder.TimestampValue */ :\n return function(t, e) {\n if (\"string\" == typeof t.timestampValue && \"string\" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) \n // Use string equality for ISO 8601 timestamps\n return t.timestampValue === e.timestampValue;\n const n = Wt(t.timestampValue), s = Wt(e.timestampValue);\n return n.seconds === s.seconds && n.nanos === s.nanos;\n }(t, e);\n\n case 5 /* TypeOrder.StringValue */ :\n return t.stringValue === e.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return function(t, e) {\n return Ht(t.bytesValue).isEqual(Ht(e.bytesValue));\n }(t, e);\n\n case 7 /* TypeOrder.RefValue */ :\n return t.referenceValue === e.referenceValue;\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function(t, e) {\n return zt(t.geoPointValue.latitude) === zt(e.geoPointValue.latitude) && zt(t.geoPointValue.longitude) === zt(e.geoPointValue.longitude);\n }(t, e);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function(t, e) {\n if (\"integerValue\" in t && \"integerValue\" in e) return zt(t.integerValue) === zt(e.integerValue);\n if (\"doubleValue\" in t && \"doubleValue\" in e) {\n const n = zt(t.doubleValue), s = zt(e.doubleValue);\n return n === s ? Ut(n) === Ut(s) : isNaN(n) && isNaN(s);\n }\n return !1;\n }(t, e);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return tt(t.arrayValue.values || [], e.arrayValue.values || [], ne);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t, e) {\n const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};\n if ($t(n) !== $t(s)) return !1;\n for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !ne(n[t], s[t]))) return !1;\n return !0;\n }\n /** Returns true if the ArrayValue contains the specified element. */ (t, e);\n\n default:\n return O();\n }\n}\n\nfunction se(t, e) {\n return void 0 !== (t.values || []).find((t => ne(t, e)));\n}\n\nfunction ie(t, e) {\n if (t === e) return 0;\n const n = ee(t), s = ee(e);\n if (n !== s) return Z(n, s);\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return 0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return Z(t.booleanValue, e.booleanValue);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function(t, e) {\n const n = zt(t.integerValue || t.doubleValue), s = zt(e.integerValue || e.doubleValue);\n return n < s ? -1 : n > s ? 1 : n === s ? 0 : \n // one or both are NaN.\n isNaN(n) ? isNaN(s) ? 0 : -1 : 1;\n }(t, e);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return re(t.timestampValue, e.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return re(Xt(t), Xt(e));\n\n case 5 /* TypeOrder.StringValue */ :\n return Z(t.stringValue, e.stringValue);\n\n case 6 /* TypeOrder.BlobValue */ :\n return function(t, e) {\n const n = Ht(t), s = Ht(e);\n return n.compareTo(s);\n }(t.bytesValue, e.bytesValue);\n\n case 7 /* TypeOrder.RefValue */ :\n return function(t, e) {\n const n = t.split(\"/\"), s = e.split(\"/\");\n for (let t = 0; t < n.length && t < s.length; t++) {\n const e = Z(n[t], s[t]);\n if (0 !== e) return e;\n }\n return Z(n.length, s.length);\n }(t.referenceValue, e.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function(t, e) {\n const n = Z(zt(t.latitude), zt(e.latitude));\n if (0 !== n) return n;\n return Z(zt(t.longitude), zt(e.longitude));\n }(t.geoPointValue, e.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return function(t, e) {\n const n = t.values || [], s = e.values || [];\n for (let t = 0; t < n.length && t < s.length; ++t) {\n const e = ie(n[t], s[t]);\n if (e) return e;\n }\n return Z(n.length, s.length);\n }(t.arrayValue, e.arrayValue);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t, e) {\n if (t === Zt.mapValue && e === Zt.mapValue) return 0;\n if (t === Zt.mapValue) return 1;\n if (e === Zt.mapValue) return -1;\n const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n s.sort(), r.sort();\n for (let t = 0; t < s.length && t < r.length; ++t) {\n const e = Z(s[t], r[t]);\n if (0 !== e) return e;\n const o = ie(n[s[t]], i[r[t]]);\n if (0 !== o) return o;\n }\n return Z(s.length, r.length);\n }\n /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (t.mapValue, e.mapValue);\n\n default:\n throw O();\n }\n}\n\nfunction re(t, e) {\n if (\"string\" == typeof t && \"string\" == typeof e && t.length === e.length) return Z(t, e);\n const n = Wt(t), s = Wt(e), i = Z(n.seconds, s.seconds);\n return 0 !== i ? i : Z(n.nanos, s.nanos);\n}\n\nfunction oe(t) {\n return ue(t);\n}\n\nfunction ue(t) {\n return \"nullValue\" in t ? \"null\" : \"booleanValue\" in t ? \"\" + t.booleanValue : \"integerValue\" in t ? \"\" + t.integerValue : \"doubleValue\" in t ? \"\" + t.doubleValue : \"timestampValue\" in t ? function(t) {\n const e = Wt(t);\n return `time(${e.seconds},${e.nanos})`;\n }(t.timestampValue) : \"stringValue\" in t ? t.stringValue : \"bytesValue\" in t ? Ht(t.bytesValue).toBase64() : \"referenceValue\" in t ? (n = t.referenceValue, \n ct.fromName(n).toString()) : \"geoPointValue\" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : \"arrayValue\" in t ? function(t) {\n let e = \"[\", n = !0;\n for (const s of t.values || []) n ? n = !1 : e += \",\", e += ue(s);\n return e + \"]\";\n }\n /** Returns a reference value for the provided database and key. */ (t.arrayValue) : \"mapValue\" in t ? function(t) {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const e = Object.keys(t.fields || {}).sort();\n let n = \"{\", s = !0;\n for (const i of e) s ? s = !1 : n += \",\", n += `${i}:${ue(t.fields[i])}`;\n return n + \"}\";\n }(t.mapValue) : O();\n var e, n;\n}\n\nfunction ce(t, e) {\n return {\n referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function ae(t) {\n return !!t && \"integerValue\" in t;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction he(t) {\n return !!t && \"arrayValue\" in t;\n}\n\n/** Returns true if `value` is a NullValue. */ function le(t) {\n return !!t && \"nullValue\" in t;\n}\n\n/** Returns true if `value` is NaN. */ function fe(t) {\n return !!t && \"doubleValue\" in t && isNaN(Number(t.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function de(t) {\n return !!t && \"mapValue\" in t;\n}\n\n/** Creates a deep copy of `source`. */ function _e(t) {\n if (t.geoPointValue) return {\n geoPointValue: Object.assign({}, t.geoPointValue)\n };\n if (t.timestampValue && \"object\" == typeof t.timestampValue) return {\n timestampValue: Object.assign({}, t.timestampValue)\n };\n if (t.mapValue) {\n const e = {\n mapValue: {\n fields: {}\n }\n };\n return Bt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = _e(n))), e;\n }\n if (t.arrayValue) {\n const e = {\n arrayValue: {\n values: []\n }\n };\n for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = _e(t.arrayValue.values[n]);\n return e;\n }\n return Object.assign({}, t);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function we(t) {\n return \"__max__\" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\n/** Returns the lowest value for the given value type (inclusive). */ function me(t) {\n return \"nullValue\" in t ? te : \"booleanValue\" in t ? {\n booleanValue: !1\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n doubleValue: NaN\n } : \"timestampValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"stringValue\" in t ? {\n stringValue: \"\"\n } : \"bytesValue\" in t ? {\n bytesValue: \"\"\n } : \"referenceValue\" in t ? ce(Ft.empty(), ct.empty()) : \"geoPointValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"arrayValue\" in t ? {\n arrayValue: {}\n } : \"mapValue\" in t ? {\n mapValue: {}\n } : O();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function ge(t) {\n return \"nullValue\" in t ? {\n booleanValue: !1\n } : \"booleanValue\" in t ? {\n doubleValue: NaN\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"timestampValue\" in t ? {\n stringValue: \"\"\n } : \"stringValue\" in t ? {\n bytesValue: \"\"\n } : \"bytesValue\" in t ? ce(Ft.empty(), ct.empty()) : \"referenceValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"geoPointValue\" in t ? {\n arrayValue: {}\n } : \"arrayValue\" in t ? {\n mapValue: {}\n } : \"mapValue\" in t ? Zt : O();\n}\n\nfunction ye(t, e) {\n const n = ie(t.value, e.value);\n return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;\n}\n\nfunction pe(t, e) {\n const n = ie(t.value, e.value);\n return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */ class Ie {\n constructor(t, e) {\n this.position = t, this.inclusive = e;\n }\n}\n\nfunction Te(t, e, n) {\n let s = 0;\n for (let i = 0; i < t.position.length; i++) {\n const r = e[i], o = t.position[i];\n if (r.field.isKeyField()) s = ct.comparator(ct.fromName(o.referenceValue), n.key); else {\n s = ie(o, n.data.field(r.field));\n }\n if (\"desc\" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;\n }\n return s;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function Ee(t, e) {\n if (null === t) return null === e;\n if (null === e) return !1;\n if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;\n for (let n = 0; n < t.position.length; n++) {\n if (!ne(t.position[n], e.position[n])) return !1;\n }\n return !0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Ae {}\n\nclass Re extends Ae {\n constructor(t, e, n) {\n super(), this.field = t, this.op = e, this.value = n;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e, n) {\n return t.isKeyField() ? \"in\" /* Operator.IN */ === e || \"not-in\" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new ke(t, e, n) : \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e ? new $e(t, n) : \"in\" /* Operator.IN */ === e ? new Be(t, n) : \"not-in\" /* Operator.NOT_IN */ === e ? new Le(t, n) : \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new qe(t, n) : new Re(t, e, n);\n }\n static createKeyFieldInFilter(t, e, n) {\n return \"in\" /* Operator.IN */ === e ? new Oe(t, n) : new Me(t, n);\n }\n matches(t) {\n const e = t.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n return \"!=\" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(ie(e, this.value)) : null !== e && ee(this.value) === ee(e) && this.matchesComparison(ie(e, this.value));\n // Only compare types with matching backend order (such as double and int).\n }\n matchesComparison(t) {\n switch (this.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n return t < 0;\n\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n return t <= 0;\n\n case \"==\" /* Operator.EQUAL */ :\n return 0 === t;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return 0 !== t;\n\n case \">\" /* Operator.GREATER_THAN */ :\n return t > 0;\n\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n return t >= 0;\n\n default:\n return O();\n }\n }\n isInequality() {\n return [ \"<\" /* Operator.LESS_THAN */ , \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ , \">\" /* Operator.GREATER_THAN */ , \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ , \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;\n }\n getFlattenedFilters() {\n return [ this ];\n }\n getFilters() {\n return [ this ];\n }\n getFirstInequalityField() {\n return this.isInequality() ? this.field : null;\n }\n}\n\nclass be extends Ae {\n constructor(t, e) {\n super(), this.filters = t, this.op = e, this.ht = null;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e) {\n return new be(t, e);\n }\n matches(t) {\n return Pe(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));\n }\n getFlattenedFilters() {\n return null !== this.ht || (this.ht = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), \n this.ht;\n }\n // Returns a mutable copy of `this.filters`\n getFilters() {\n return Object.assign([], this.filters);\n }\n getFirstInequalityField() {\n const t = this.lt((t => t.isInequality()));\n return null !== t ? t.field : null;\n }\n // Performs a depth-first search to find and return the first FieldFilter in the composite filter\n // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the\n // predicate.\n lt(t) {\n for (const e of this.getFlattenedFilters()) if (t(e)) return e;\n return null;\n }\n}\n\nfunction Pe(t) {\n return \"and\" /* CompositeOperator.AND */ === t.op;\n}\n\nfunction ve(t) {\n return \"or\" /* CompositeOperator.OR */ === t.op;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */ function Ve(t) {\n return Se(t) && Pe(t);\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */ function Se(t) {\n for (const e of t.filters) if (e instanceof be) return !1;\n return !0;\n}\n\nfunction De(t) {\n if (t instanceof Re) \n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return t.field.canonicalString() + t.op.toString() + oe(t.value);\n if (Ve(t)) \n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return t.filters.map((t => De(t))).join(\",\");\n {\n // filter instanceof CompositeFilter\n const e = t.filters.map((t => De(t))).join(\",\");\n return `${t.op}(${e})`;\n }\n}\n\nfunction Ce(t, e) {\n return t instanceof Re ? function(t, e) {\n return e instanceof Re && t.op === e.op && t.field.isEqual(e.field) && ne(t.value, e.value);\n }(t, e) : t instanceof be ? function(t, e) {\n if (e instanceof be && t.op === e.op && t.filters.length === e.filters.length) {\n return t.filters.reduce(((t, n, s) => t && Ce(n, e.filters[s])), !0);\n }\n return !1;\n }\n /**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */ (t, e) : void O();\n}\n\nfunction xe(t, e) {\n const n = t.filters.concat(e);\n return be.create(n, t.op);\n}\n\n/** Returns a debug description for `filter`. */ function Ne(t) {\n return t instanceof Re ? function(t) {\n return `${t.field.canonicalString()} ${t.op} ${oe(t.value)}`;\n }\n /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof be ? function(t) {\n return t.op.toString() + \" {\" + t.getFilters().map(Ne).join(\" ,\") + \"}\";\n }(t) : \"Filter\";\n}\n\nclass ke extends Re {\n constructor(t, e, n) {\n super(t, e, n), this.key = ct.fromName(n.referenceValue);\n }\n matches(t) {\n const e = ct.comparator(t.key, this.key);\n return this.matchesComparison(e);\n }\n}\n\n/** Filter that matches on key fields within an array. */ class Oe extends Re {\n constructor(t, e) {\n super(t, \"in\" /* Operator.IN */ , e), this.keys = Fe(\"in\" /* Operator.IN */ , e);\n }\n matches(t) {\n return this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */ class Me extends Re {\n constructor(t, e) {\n super(t, \"not-in\" /* Operator.NOT_IN */ , e), this.keys = Fe(\"not-in\" /* Operator.NOT_IN */ , e);\n }\n matches(t) {\n return !this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\nfunction Fe(t, e) {\n var n;\n return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ct.fromName(t.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class $e extends Re {\n constructor(t, e) {\n super(t, \"array-contains\" /* Operator.ARRAY_CONTAINS */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return he(e) && se(e.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */ class Be extends Re {\n constructor(t, e) {\n super(t, \"in\" /* Operator.IN */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return null !== e && se(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the not-in operator. */ class Le extends Re {\n constructor(t, e) {\n super(t, \"not-in\" /* Operator.NOT_IN */ , e);\n }\n matches(t) {\n if (se(this.value.arrayValue, {\n nullValue: \"NULL_VALUE\"\n })) return !1;\n const e = t.data.field(this.field);\n return null !== e && !se(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class qe extends Re {\n constructor(t, e) {\n super(t, \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return !(!he(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => se(this.value.arrayValue, t)));\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class Ue {\n constructor(t, e = \"asc\" /* Direction.ASCENDING */) {\n this.field = t, this.dir = e;\n }\n}\n\nfunction Ke(t, e) {\n return t.dir === e.dir && t.field.isEqual(e.field);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass Ge {\n constructor(t, e) {\n this.comparator = t, this.root = e || je.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(t, e) {\n return new Ge(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, je.BLACK, null, null));\n }\n // Returns a copy of the map, with the specified key removed.\n remove(t) {\n return new Ge(this.comparator, this.root.remove(t, this.comparator).copy(null, null, je.BLACK, null, null));\n }\n // Returns the value of the node with the given key, or null.\n get(t) {\n let e = this.root;\n for (;!e.isEmpty(); ) {\n const n = this.comparator(t, e.key);\n if (0 === n) return e.value;\n n < 0 ? e = e.left : n > 0 && (e = e.right);\n }\n return null;\n }\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(t) {\n // Number of nodes that were pruned when descending right\n let e = 0, n = this.root;\n for (;!n.isEmpty(); ) {\n const s = this.comparator(t, n.key);\n if (0 === s) return e + n.left.size;\n s < 0 ? n = n.left : (\n // Count all nodes left of the node plus the node itself\n e += n.left.size + 1, n = n.right);\n }\n // Node not found\n return -1;\n }\n isEmpty() {\n return this.root.isEmpty();\n }\n // Returns the total number of nodes in the map.\n get size() {\n return this.root.size;\n }\n // Returns the minimum key in the map.\n minKey() {\n return this.root.minKey();\n }\n // Returns the maximum key in the map.\n maxKey() {\n return this.root.maxKey();\n }\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.root.inorderTraversal(t);\n }\n forEach(t) {\n this.inorderTraversal(((e, n) => (t(e, n), !1)));\n }\n toString() {\n const t = [];\n return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(\", \")}}`;\n }\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.root.reverseTraversal(t);\n }\n // Returns an iterator over the SortedMap.\n getIterator() {\n return new Qe(this.root, null, this.comparator, !1);\n }\n getIteratorFrom(t) {\n return new Qe(this.root, t, this.comparator, !1);\n }\n getReverseIterator() {\n return new Qe(this.root, null, this.comparator, !0);\n }\n getReverseIteratorFrom(t) {\n return new Qe(this.root, t, this.comparator, !0);\n }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass Qe {\n constructor(t, e, n, s) {\n this.isReverse = s, this.nodeStack = [];\n let i = 1;\n for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1, \n // flip the comparison if we're going in reverse\n e && s && (i *= -1), i < 0) \n // This node is less than our start key. ignore it\n t = this.isReverse ? t.left : t.right; else {\n if (0 === i) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(t);\n break;\n }\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;\n }\n }\n getNext() {\n let t = this.nodeStack.pop();\n const e = {\n key: t.key,\n value: t.value\n };\n if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), \n t = t.left;\n return e;\n }\n hasNext() {\n return this.nodeStack.length > 0;\n }\n peek() {\n if (0 === this.nodeStack.length) return null;\n const t = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: t.key,\n value: t.value\n };\n }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass je {\n constructor(t, e, n, s, i) {\n this.key = t, this.value = e, this.color = null != n ? n : je.RED, this.left = null != s ? s : je.EMPTY, \n this.right = null != i ? i : je.EMPTY, this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(t, e, n, s, i) {\n return new je(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);\n }\n isEmpty() {\n return !1;\n }\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);\n }\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);\n }\n // Returns the minimum node in the tree.\n min() {\n return this.left.isEmpty() ? this : this.left.min();\n }\n // Returns the maximum key in the tree.\n minKey() {\n return this.min().key;\n }\n // Returns the maximum key in the tree.\n maxKey() {\n return this.right.isEmpty() ? this.key : this.right.maxKey();\n }\n // Returns new tree, with the key/value added.\n insert(t, e, n) {\n let s = this;\n const i = n(t, s.key);\n return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)), \n s.fixUp();\n }\n removeMin() {\n if (this.left.isEmpty()) return je.EMPTY;\n let t = this;\n return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), \n t.fixUp();\n }\n // Returns new tree, with the specified item removed.\n remove(t, e) {\n let n, s = this;\n if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()), \n s = s.copy(null, null, null, s.left.remove(t, e), null); else {\n if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()), \n 0 === e(t, s.key)) {\n if (s.right.isEmpty()) return je.EMPTY;\n n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());\n }\n s = s.copy(null, null, null, null, s.right.remove(t, e));\n }\n return s.fixUp();\n }\n isRed() {\n return this.color;\n }\n // Returns new tree after performing any needed rotations.\n fixUp() {\n let t = this;\n return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), \n t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;\n }\n moveRedLeft() {\n let t = this.colorFlip();\n return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), \n t = t.rotateLeft(), t = t.colorFlip()), t;\n }\n moveRedRight() {\n let t = this.colorFlip();\n return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;\n }\n rotateLeft() {\n const t = this.copy(null, null, je.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, t, null);\n }\n rotateRight() {\n const t = this.copy(null, null, je.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, t);\n }\n colorFlip() {\n const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, t, e);\n }\n // For testing.\n checkMaxDepth() {\n const t = this.check();\n return Math.pow(2, t) <= this.size + 1;\n }\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n check() {\n if (this.isRed() && this.left.isRed()) throw O();\n if (this.right.isRed()) throw O();\n const t = this.left.check();\n if (t !== this.right.check()) throw O();\n return t + (this.isRed() ? 0 : 1);\n }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nje.EMPTY = null, je.RED = !0, je.BLACK = !1;\n\n// end LLRBEmptyNode\nje.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass {\n constructor() {\n this.size = 0;\n }\n get key() {\n throw O();\n }\n get value() {\n throw O();\n }\n get color() {\n throw O();\n }\n get left() {\n throw O();\n }\n get right() {\n throw O();\n }\n // Returns a copy of the current node.\n copy(t, e, n, s, i) {\n return this;\n }\n // Returns a copy of the tree, with the specified key/value added.\n insert(t, e, n) {\n return new je(t, e);\n }\n // Returns a copy of the tree, with the specified key removed.\n remove(t, e) {\n return this;\n }\n isEmpty() {\n return !0;\n }\n inorderTraversal(t) {\n return !1;\n }\n reverseTraversal(t) {\n return !1;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n isRed() {\n return !1;\n }\n // For testing.\n checkMaxDepth() {\n return !0;\n }\n check() {\n return 0;\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass We {\n constructor(t) {\n this.comparator = t, this.data = new Ge(this.comparator);\n }\n has(t) {\n return null !== this.data.get(t);\n }\n first() {\n return this.data.minKey();\n }\n last() {\n return this.data.maxKey();\n }\n get size() {\n return this.data.size;\n }\n indexOf(t) {\n return this.data.indexOf(t);\n }\n /** Iterates elements in order defined by \"comparator\" */ forEach(t) {\n this.data.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {\n const n = this.data.getIteratorFrom(t[0]);\n for (;n.hasNext(); ) {\n const s = n.getNext();\n if (this.comparator(s.key, t[1]) >= 0) return;\n e(s.key);\n }\n }\n /**\n * Iterates over `elem`s such that: start &lt;= elem until false is returned.\n */ forEachWhile(t, e) {\n let n;\n for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {\n if (!t(n.getNext().key)) return;\n }\n }\n /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {\n const e = this.data.getIteratorFrom(t);\n return e.hasNext() ? e.getNext().key : null;\n }\n getIterator() {\n return new ze(this.data.getIterator());\n }\n getIteratorFrom(t) {\n return new ze(this.data.getIteratorFrom(t));\n }\n /** Inserts or updates an element */ add(t) {\n return this.copy(this.data.remove(t).insert(t, !0));\n }\n /** Deletes an element */ delete(t) {\n return this.has(t) ? this.copy(this.data.remove(t)) : this;\n }\n isEmpty() {\n return this.data.isEmpty();\n }\n unionWith(t) {\n let e = this;\n // Make sure `result` always refers to the larger one of the two sets.\n return e.size < t.size && (e = t, t = this), t.forEach((t => {\n e = e.add(t);\n })), e;\n }\n isEqual(t) {\n if (!(t instanceof We)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.data.getIterator(), n = t.data.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (0 !== this.comparator(t, s)) return !1;\n }\n return !0;\n }\n toArray() {\n const t = [];\n return this.forEach((e => {\n t.push(e);\n })), t;\n }\n toString() {\n const t = [];\n return this.forEach((e => t.push(e))), \"SortedSet(\" + t.toString() + \")\";\n }\n copy(t) {\n const e = new We(this.comparator);\n return e.data = t, e;\n }\n}\n\nclass ze {\n constructor(t) {\n this.iter = t;\n }\n getNext() {\n return this.iter.getNext().key;\n }\n hasNext() {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction He(t) {\n return t.hasNext() ? t.getNext() : void 0;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */ class Je {\n constructor(t) {\n this.fields = t, \n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n t.sort(ut.comparator);\n }\n static empty() {\n return new Je([]);\n }\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */ unionWith(t) {\n let e = new We(ut.comparator);\n for (const t of this.fields) e = e.add(t);\n for (const n of t) e = e.add(n);\n return new Je(e.toArray());\n }\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */ covers(t) {\n for (const e of this.fields) if (e.isPrefixOf(t)) return !0;\n return !1;\n }\n isEqual(t) {\n return tt(this.fields, t.fields, ((t, e) => t.isEqual(e)));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class Ye {\n constructor(t) {\n this.value = t;\n }\n static empty() {\n return new Ye({\n mapValue: {}\n });\n }\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */ field(t) {\n if (t.isEmpty()) return this.value;\n {\n let e = this.value;\n for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)], \n !de(e)) return null;\n return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;\n }\n }\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */ set(t, e) {\n this.getFieldsMap(t.popLast())[t.lastSegment()] = _e(e);\n }\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */ setAll(t) {\n let e = ut.emptyPath(), n = {}, s = [];\n t.forEach(((t, i) => {\n if (!e.isImmediateParentOf(i)) {\n // Insert the accumulated changes at this parent location\n const t = this.getFieldsMap(e);\n this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();\n }\n t ? n[i.lastSegment()] = _e(t) : s.push(i.lastSegment());\n }));\n const i = this.getFieldsMap(e);\n this.applyChanges(i, n, s);\n }\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */ delete(t) {\n const e = this.field(t.popLast());\n de(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];\n }\n isEqual(t) {\n return ne(this.value, t.value);\n }\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */ getFieldsMap(t) {\n let e = this.value;\n e.mapValue.fields || (e.mapValue = {\n fields: {}\n });\n for (let n = 0; n < t.length; ++n) {\n let s = e.mapValue.fields[t.get(n)];\n de(s) && s.mapValue.fields || (s = {\n mapValue: {\n fields: {}\n }\n }, e.mapValue.fields[t.get(n)] = s), e = s;\n }\n return e.mapValue.fields;\n }\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */ applyChanges(t, e, n) {\n Bt(e, ((e, n) => t[e] = n));\n for (const e of n) delete t[e];\n }\n clone() {\n return new Ye(_e(this.value));\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function Xe(t) {\n const e = [];\n return Bt(t.fields, ((t, n) => {\n const s = new ut([ t ]);\n if (de(n)) {\n const t = Xe(n.mapValue).fields;\n if (0 === t.length) \n // Preserve the empty map by adding it to the FieldMask.\n e.push(s); else \n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const n of t) e.push(s.child(n));\n } else \n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n e.push(s);\n })), new Je(e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class Ze {\n constructor(t, e, n, s, i, r, o) {\n this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i, \n this.data = r, this.documentState = o;\n }\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */ static newInvalidDocument(t) {\n return new Ze(t, 0 /* DocumentType.INVALID */ , \n /* version */ st.min(), \n /* readTime */ st.min(), \n /* createTime */ st.min(), Ye.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */ static newFoundDocument(t, e, n, s) {\n return new Ze(t, 1 /* DocumentType.FOUND_DOCUMENT */ , \n /* version */ e, \n /* readTime */ st.min(), \n /* createTime */ n, s, 0 /* DocumentState.SYNCED */);\n }\n /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {\n return new Ze(t, 2 /* DocumentType.NO_DOCUMENT */ , \n /* version */ e, \n /* readTime */ st.min(), \n /* createTime */ st.min(), Ye.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */ static newUnknownDocument(t, e) {\n return new Ze(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n /* version */ e, \n /* readTime */ st.min(), \n /* createTime */ st.min(), Ye.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);\n }\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */ convertToFoundDocument(t, e) {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n return !this.createTime.isEqual(st.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), \n this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, \n this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */ convertToNoDocument(t) {\n return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , \n this.data = Ye.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */ convertToUnknownDocument(t) {\n return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n this.data = Ye.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , \n this;\n }\n setHasCommittedMutations() {\n return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasLocalMutations() {\n return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = st.min(), \n this;\n }\n setReadTime(t) {\n return this.readTime = t, this;\n }\n get hasLocalMutations() {\n return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;\n }\n get hasCommittedMutations() {\n return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;\n }\n get hasPendingWrites() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n isValidDocument() {\n return 0 /* DocumentType.INVALID */ !== this.documentType;\n }\n isFoundDocument() {\n return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;\n }\n isNoDocument() {\n return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;\n }\n isUnknownDocument() {\n return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;\n }\n isEqual(t) {\n return t instanceof Ze && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);\n }\n mutableCopy() {\n return new Ze(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);\n }\n toString() {\n return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass tn {\n constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i, \n this.startAt = r, this.endAt = o, this.ft = null;\n }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function en(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n return new tn(t, e, n, s, i, r, o);\n}\n\nfunction nn(t) {\n const e = $(t);\n if (null === e.ft) {\n let t = e.path.canonicalString();\n null !== e.collectionGroup && (t += \"|cg:\" + e.collectionGroup), t += \"|f:\", t += e.filters.map((t => De(t))).join(\",\"), \n t += \"|ob:\", t += e.orderBy.map((t => function(t) {\n // TODO(b/29183165): Make this collision robust.\n return t.field.canonicalString() + t.dir;\n }(t))).join(\",\"), qt(e.limit) || (t += \"|l:\", t += e.limit), e.startAt && (t += \"|lb:\", \n t += e.startAt.inclusive ? \"b:\" : \"a:\", t += e.startAt.position.map((t => oe(t))).join(\",\")), \n e.endAt && (t += \"|ub:\", t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((t => oe(t))).join(\",\")), \n e.ft = t;\n }\n return e.ft;\n}\n\nfunction sn(t, e) {\n if (t.limit !== e.limit) return !1;\n if (t.orderBy.length !== e.orderBy.length) return !1;\n for (let n = 0; n < t.orderBy.length; n++) if (!Ke(t.orderBy[n], e.orderBy[n])) return !1;\n if (t.filters.length !== e.filters.length) return !1;\n for (let n = 0; n < t.filters.length; n++) if (!Ce(t.filters[n], e.filters[n])) return !1;\n return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!Ee(t.startAt, e.startAt) && Ee(t.endAt, e.endAt)));\n}\n\nfunction rn(t) {\n return ct.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function on(t, e) {\n return t.filters.filter((t => t instanceof Re && t.field.isEqual(e)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction un(t, e, n) {\n let s = te, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of on(t, e)) {\n let t = te, e = !0;\n switch (n.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n t = me(n.value);\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \">\" /* Operator.GREATER_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n t = te;\n // Remaining filters cannot be used as lower bounds.\n }\n ye({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: e\n }) < 0 && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n ye({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: n.inclusive\n }) < 0 && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */ function cn(t, e, n) {\n let s = Zt, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of on(t, e)) {\n let t = Zt, e = !0;\n switch (n.op) {\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n case \">\" /* Operator.GREATER_THAN */ :\n t = ge(n.value), e = !1;\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \"<\" /* Operator.LESS_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n t = Zt;\n // Remaining filters cannot be used as upper bounds.\n }\n pe({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: e\n }) > 0 && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n pe({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: n.inclusive\n }) > 0 && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nclass an {\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(t, e = null, n = [], s = [], i = null, r = \"F\" /* LimitType.First */ , o = null, u = null) {\n this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s, \n this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.dt = null, \n // The corresponding `Target` of this `Query` instance.\n this._t = null, this.startAt, this.endAt;\n }\n}\n\n/** Creates a new Query instance with the options provided. */ function hn(t, e, n, s, i, r, o, u) {\n return new an(t, e, n, s, i, r, o, u);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function ln(t) {\n return new an(t);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nfunction fn(t) {\n return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());\n}\n\nfunction dn(t) {\n return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;\n}\n\nfunction _n(t) {\n for (const e of t.filters) {\n const t = e.getFirstInequalityField();\n if (null !== t) return t;\n }\n return null;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction wn(t) {\n return null !== t.collectionGroup;\n}\n\n/**\n * Returns the implicit order by constraint that is used to execute the Query,\n * which can be different from the order by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`).\n */ function mn(t) {\n const e = $(t);\n if (null === e.dt) {\n e.dt = [];\n const t = _n(e), n = dn(e);\n if (null !== t && null === n) \n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n t.isKeyField() || e.dt.push(new Ue(t)), e.dt.push(new Ue(ut.keyField(), \"asc\" /* Direction.ASCENDING */)); else {\n let t = !1;\n for (const n of e.explicitOrderBy) e.dt.push(n), n.field.isKeyField() && (t = !0);\n if (!t) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : \"asc\" /* Direction.ASCENDING */;\n e.dt.push(new Ue(ut.keyField(), t));\n }\n }\n }\n return e.dt;\n}\n\n/**\n * Converts this `Query` instance to it's corresponding `Target` representation.\n */ function gn(t) {\n const e = $(t);\n if (!e._t) if (\"F\" /* LimitType.First */ === e.limitType) e._t = en(e.path, e.collectionGroup, mn(e), e.filters, e.limit, e.startAt, e.endAt); else {\n // Flip the orderBy directions since we want the last results\n const t = [];\n for (const n of mn(e)) {\n const e = \"desc\" /* Direction.DESCENDING */ === n.dir ? \"asc\" /* Direction.ASCENDING */ : \"desc\" /* Direction.DESCENDING */;\n t.push(new Ue(n.field, e));\n }\n // We need to swap the cursors to match the now-flipped query ordering.\n const n = e.endAt ? new Ie(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new Ie(e.startAt.position, e.startAt.inclusive) : null;\n // Now return as a LimitType.First query.\n e._t = en(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);\n }\n return e._t;\n}\n\nfunction yn(t, e) {\n e.getFirstInequalityField(), _n(t);\n const n = t.filters.concat([ e ]);\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);\n}\n\nfunction pn(t, e, n) {\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);\n}\n\nfunction In(t, e) {\n return sn(gn(t), gn(e)) && t.limitType === e.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction Tn(t) {\n return `${nn(gn(t))}|lt:${t.limitType}`;\n}\n\nfunction En(t) {\n return `Query(target=${function(t) {\n let e = t.path.canonicalString();\n return null !== t.collectionGroup && (e += \" collectionGroup=\" + t.collectionGroup), \n t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Ne(t))).join(\", \")}]`), \n qt(t.limit) || (e += \", limit: \" + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {\n return `${t.field.canonicalString()} (${t.dir})`;\n }(t))).join(\", \")}]`), t.startAt && (e += \", startAt: \", e += t.startAt.inclusive ? \"b:\" : \"a:\", \n e += t.startAt.position.map((t => oe(t))).join(\",\")), t.endAt && (e += \", endAt: \", \n e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((t => oe(t))).join(\",\")), \n `Target(${e})`;\n }(gn(t))}; limitType=${t.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function An(t, e) {\n return e.isFoundDocument() && function(t, e) {\n const n = e.key.path;\n return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ct.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);\n }\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (t, e) && function(t, e) {\n // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const n of mn(t)) \n // order by key always matches\n if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;\n return !0;\n }(t, e) && function(t, e) {\n for (const n of t.filters) if (!n.matches(e)) return !1;\n return !0;\n }\n /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {\n if (t.startAt && !\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n function(t, e, n) {\n const s = Te(t, e, n);\n return t.inclusive ? s <= 0 : s < 0;\n }(t.startAt, mn(t), e)) return !1;\n if (t.endAt && !function(t, e, n) {\n const s = Te(t, e, n);\n return t.inclusive ? s >= 0 : s > 0;\n }(t.endAt, mn(t), e)) return !1;\n return !0;\n }\n /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (t, e);\n}\n\nfunction Rn(t) {\n return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function bn(t) {\n return (e, n) => {\n let s = !1;\n for (const i of mn(t)) {\n const t = Pn(i, e, n);\n if (0 !== t) return t;\n s = s || i.field.isKeyField();\n }\n return 0;\n };\n}\n\nfunction Pn(t, e, n) {\n const s = t.field.isKeyField() ? ct.comparator(e.key, n.key) : function(t, e, n) {\n const s = e.data.field(t), i = n.data.field(t);\n return null !== s && null !== i ? ie(s, i) : O();\n }(t.field, e, n);\n switch (t.dir) {\n case \"asc\" /* Direction.ASCENDING */ :\n return s;\n\n case \"desc\" /* Direction.DESCENDING */ :\n return -1 * s;\n\n default:\n return O();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function vn(t, e) {\n if (t.wt) {\n if (isNaN(e)) return {\n doubleValue: \"NaN\"\n };\n if (e === 1 / 0) return {\n doubleValue: \"Infinity\"\n };\n if (e === -1 / 0) return {\n doubleValue: \"-Infinity\"\n };\n }\n return {\n doubleValue: Ut(e) ? \"-0\" : e\n };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function Vn(t) {\n return {\n integerValue: \"\" + t\n };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function Sn(t, e) {\n return Kt(e) ? Vn(e) : vn(t, e);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Used to represent a field transform on a mutation. */ class Dn {\n constructor() {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n this._ = void 0;\n }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function Cn(t, e, n) {\n return t instanceof kn ? function(t, e) {\n const n = {\n fields: {\n __type__: {\n stringValue: \"server_timestamp\"\n },\n __local_write_time__: {\n timestampValue: {\n seconds: t.seconds,\n nanos: t.nanoseconds\n }\n }\n }\n };\n return e && (n.fields.__previous_value__ = e), {\n mapValue: n\n };\n }(n, e) : t instanceof On ? Mn(t, e) : t instanceof Fn ? $n(t, e) : function(t, e) {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const n = Nn(t, e), s = Ln(n) + Ln(t.gt);\n return ae(n) && ae(t.gt) ? Vn(s) : vn(t.yt, s);\n }(t, e);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function xn(t, e, n) {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return t instanceof On ? Mn(t, e) : t instanceof Fn ? $n(t, e) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function Nn(t, e) {\n return t instanceof Bn ? ae(n = e) || function(t) {\n return !!t && \"doubleValue\" in t;\n }\n /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {\n integerValue: 0\n } : null;\n var n;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass kn extends Dn {}\n\n/** Transforms an array value via a union operation. */ class On extends Dn {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction Mn(t, e) {\n const n = qn(e);\n for (const e of t.elements) n.some((t => ne(t, e))) || n.push(e);\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/** Transforms an array value via a remove operation. */ class Fn extends Dn {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction $n(t, e) {\n let n = qn(e);\n for (const e of t.elements) n = n.filter((t => !ne(t, e)));\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class Bn extends Dn {\n constructor(t, e) {\n super(), this.yt = t, this.gt = e;\n }\n}\n\nfunction Ln(t) {\n return zt(t.integerValue || t.doubleValue);\n}\n\nfunction qn(t) {\n return he(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class Un {\n constructor(t, e) {\n this.field = t, this.transform = e;\n }\n}\n\nfunction Kn(t, e) {\n return t.field.isEqual(e.field) && function(t, e) {\n return t instanceof On && e instanceof On || t instanceof Fn && e instanceof Fn ? tt(t.elements, e.elements, ne) : t instanceof Bn && e instanceof Bn ? ne(t.gt, e.gt) : t instanceof kn && e instanceof kn;\n }(t.transform, e.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass Gn {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n t, \n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n e) {\n this.version = t, this.transformResults = e;\n }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class Qn {\n constructor(t, e) {\n this.updateTime = t, this.exists = e;\n }\n /** Creates a new empty Precondition. */ static none() {\n return new Qn;\n }\n /** Creates a new Precondition with an exists flag. */ static exists(t) {\n return new Qn(void 0, t);\n }\n /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {\n return new Qn(t);\n }\n /** Returns whether this Precondition is empty. */ get isNone() {\n return void 0 === this.updateTime && void 0 === this.exists;\n }\n isEqual(t) {\n return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function jn(t, e) {\n return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class Wn {}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */ function zn(t, e) {\n if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;\n // mask is null when sets or deletes are applied to the current document.\n if (null === e) return t.isNoDocument() ? new is(t.key, Qn.none()) : new Zn(t.key, t.data, Qn.none());\n {\n const n = t.data, s = Ye.empty();\n let i = new We(ut.comparator);\n for (let t of e.fields) if (!i.has(t)) {\n let e = n.field(t);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e), \n i = i.add(t);\n }\n return new ts(t.key, s, new Je(i.toArray()), Qn.none());\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function Hn(t, e, n) {\n t instanceof Zn ? function(t, e, n) {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const s = t.value.clone(), i = ns(t.fieldTransforms, e, n.transformResults);\n s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();\n }(t, e, n) : t instanceof ts ? function(t, e, n) {\n if (!jn(t.precondition, e)) \n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n return void e.convertToUnknownDocument(n.version);\n const s = ns(t.fieldTransforms, e, n.transformResults), i = e.data;\n i.setAll(es(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n }(t, e, n) : function(t, e, n) {\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n e.convertToNoDocument(n.version).setHasCommittedMutations();\n }(0, e, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */ function Jn(t, e, n, s) {\n return t instanceof Zn ? function(t, e, n, s) {\n if (!jn(t.precondition, e)) \n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return n;\n const i = t.value.clone(), r = ss(t.fieldTransforms, s, e);\n return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(), \n null;\n // SetMutation overwrites all fields.\n }\n /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */ (t, e, n, s) : t instanceof ts ? function(t, e, n, s) {\n if (!jn(t.precondition, e)) return n;\n const i = ss(t.fieldTransforms, s, e), r = e.data;\n if (r.setAll(es(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(), \n null === n) return null;\n return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));\n }\n /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (t, e, n, s) : function(t, e, n) {\n if (jn(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(), \n null;\n return n;\n }\n /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (t, e, n);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function Yn(t, e) {\n let n = null;\n for (const s of t.fieldTransforms) {\n const t = e.data.field(s.field), i = Nn(s.transform, t || null);\n null != i && (null === n && (n = Ye.empty()), n.set(s.field, i));\n }\n return n || null;\n}\n\nfunction Xn(t, e) {\n return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {\n return void 0 === t && void 0 === e || !(!t || !e) && tt(t, e, ((t, e) => Kn(t, e)));\n }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class Zn extends Wn {\n constructor(t, e, n, s = []) {\n super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s, \n this.type = 0 /* MutationType.Set */;\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass ts extends Wn {\n constructor(t, e, n, s, i = []) {\n super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s, \n this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;\n }\n getFieldMask() {\n return this.fieldMask;\n }\n}\n\nfunction es(t) {\n const e = new Map;\n return t.fieldMask.fields.forEach((n => {\n if (!n.isEmpty()) {\n const s = t.data.field(n);\n e.set(n, s);\n }\n })), e;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function ns(t, e, n) {\n const s = new Map;\n M(t.length === n.length);\n for (let i = 0; i < n.length; i++) {\n const r = t[i], o = r.transform, u = e.data.field(r.field);\n s.set(r.field, xn(o, u, n[i]));\n }\n return s;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */ function ss(t, e, n) {\n const s = new Map;\n for (const i of t) {\n const t = i.transform, r = n.data.field(i.field);\n s.set(i.field, Cn(t, r, e));\n }\n return s;\n}\n\n/** A mutation that deletes the document at the given key. */ class is extends Wn {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass rs extends Wn {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class os {\n // TODO(b/33078163): just use simplest form of existence filter for now\n constructor(t) {\n this.count = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var us, cs;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction as(t) {\n switch (t) {\n default:\n return O();\n\n case B.CANCELLED:\n case B.UNKNOWN:\n case B.DEADLINE_EXCEEDED:\n case B.RESOURCE_EXHAUSTED:\n case B.INTERNAL:\n case B.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case B.UNAUTHENTICATED:\n return !1;\n\n case B.INVALID_ARGUMENT:\n case B.NOT_FOUND:\n case B.ALREADY_EXISTS:\n case B.PERMISSION_DENIED:\n case B.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case B.ABORTED:\n case B.OUT_OF_RANGE:\n case B.UNIMPLEMENTED:\n case B.DATA_LOSS:\n return !0;\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction hs(t) {\n if (void 0 === t) \n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n return x(\"GRPC error has no .code\"), B.UNKNOWN;\n switch (t) {\n case us.OK:\n return B.OK;\n\n case us.CANCELLED:\n return B.CANCELLED;\n\n case us.UNKNOWN:\n return B.UNKNOWN;\n\n case us.DEADLINE_EXCEEDED:\n return B.DEADLINE_EXCEEDED;\n\n case us.RESOURCE_EXHAUSTED:\n return B.RESOURCE_EXHAUSTED;\n\n case us.INTERNAL:\n return B.INTERNAL;\n\n case us.UNAVAILABLE:\n return B.UNAVAILABLE;\n\n case us.UNAUTHENTICATED:\n return B.UNAUTHENTICATED;\n\n case us.INVALID_ARGUMENT:\n return B.INVALID_ARGUMENT;\n\n case us.NOT_FOUND:\n return B.NOT_FOUND;\n\n case us.ALREADY_EXISTS:\n return B.ALREADY_EXISTS;\n\n case us.PERMISSION_DENIED:\n return B.PERMISSION_DENIED;\n\n case us.FAILED_PRECONDITION:\n return B.FAILED_PRECONDITION;\n\n case us.ABORTED:\n return B.ABORTED;\n\n case us.OUT_OF_RANGE:\n return B.OUT_OF_RANGE;\n\n case us.UNIMPLEMENTED:\n return B.UNIMPLEMENTED;\n\n case us.DATA_LOSS:\n return B.DATA_LOSS;\n\n default:\n return O();\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */ (cs = us || (us = {}))[cs.OK = 0] = \"OK\", cs[cs.CANCELLED = 1] = \"CANCELLED\", \ncs[cs.UNKNOWN = 2] = \"UNKNOWN\", cs[cs.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \ncs[cs.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", cs[cs.NOT_FOUND = 5] = \"NOT_FOUND\", \ncs[cs.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", cs[cs.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \ncs[cs.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", cs[cs.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \ncs[cs.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", cs[cs.ABORTED = 10] = \"ABORTED\", \ncs[cs.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", cs[cs.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \ncs[cs.INTERNAL = 13] = \"INTERNAL\", cs[cs.UNAVAILABLE = 14] = \"UNAVAILABLE\", cs[cs.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nclass ls {\n constructor(t, e) {\n this.mapKeyFn = t, this.equalsFn = e, \n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n this.inner = {}, \n /** The number of entries stored in the map */\n this.innerSize = 0;\n }\n /** Get a value for this key, or undefined if it does not exist. */ get(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;\n }\n has(t) {\n return void 0 !== this.get(t);\n }\n /** Put this key and value in the map. */ set(t, e) {\n const n = this.mapKeyFn(t), s = this.inner[n];\n if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;\n for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t)) \n // This is updating an existing entry and does not increase `innerSize`.\n return void (s[n] = [ t, e ]);\n s.push([ t, e ]), this.innerSize++;\n }\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */ delete(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 === n) return !1;\n for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1), \n this.innerSize--, !0;\n return !1;\n }\n forEach(t) {\n Bt(this.inner, ((e, n) => {\n for (const [e, s] of n) t(e, s);\n }));\n }\n isEmpty() {\n return Lt(this.inner);\n }\n size() {\n return this.innerSize;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const fs = new Ge(ct.comparator);\n\nfunction ds() {\n return fs;\n}\n\nconst _s = new Ge(ct.comparator);\n\nfunction ws(...t) {\n let e = _s;\n for (const n of t) e = e.insert(n.key, n);\n return e;\n}\n\nfunction ms(t) {\n let e = _s;\n return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;\n}\n\nfunction gs() {\n return ps();\n}\n\nfunction ys() {\n return ps();\n}\n\nfunction ps() {\n return new ls((t => t.toString()), ((t, e) => t.isEqual(e)));\n}\n\nconst Is = new Ge(ct.comparator);\n\nconst Ts = new We(ct.comparator);\n\nfunction Es(...t) {\n let e = Ts;\n for (const n of t) e = e.add(n);\n return e;\n}\n\nconst As = new We(Z);\n\nfunction Rs() {\n return As;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class bs {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n t, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n e, \n /**\n * A set of targets that is known to be inconsistent. Listens for these\n * targets should be re-established without resume tokens.\n */\n n, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n s, \n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n i) {\n this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s, \n this.resolvedLimboDocuments = i;\n }\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(t, e, n) {\n const s = new Map;\n return s.set(t, Ps.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new bs(st.min(), s, Rs(), ds(), Es());\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class Ps {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n t, \n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n e, \n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n n, \n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n s, \n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n i) {\n this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s, \n this.removedDocuments = i;\n }\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {\n return new Ps(n, e, Es(), Es(), Es());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class vs {\n constructor(\n /** The new document applies to all of these targets. */\n t, \n /** The new document is removed from all of these targets. */\n e, \n /** The key of the document for this change. */\n n, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n s) {\n this.It = t, this.removedTargetIds = e, this.key = n, this.Tt = s;\n }\n}\n\nclass Vs {\n constructor(t, e) {\n this.targetId = t, this.Et = e;\n }\n}\n\nclass Ss {\n constructor(\n /** What kind of change occurred to the watch target. */\n t, \n /** The target IDs that were added/removed/set. */\n e, \n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n n = Qt.EMPTY_BYTE_STRING\n /** An RPC error indicating why the watch failed. */ , s = null) {\n this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;\n }\n}\n\n/** Tracks the internal state of a Watch target. */ class Ds {\n constructor() {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n this.At = 0, \n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n this.Rt = Ns(), \n /** See public getters for explanations of these fields. */\n this.bt = Qt.EMPTY_BYTE_STRING, this.Pt = !1, \n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n this.vt = !0;\n }\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */ get current() {\n return this.Pt;\n }\n /** The last resume token sent to us for this target. */ get resumeToken() {\n return this.bt;\n }\n /** Whether this target has pending target adds or target removes. */ get Vt() {\n return 0 !== this.At;\n }\n /** Whether we have modified any state that should trigger a snapshot. */ get St() {\n return this.vt;\n }\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */ Dt(t) {\n t.approximateByteSize() > 0 && (this.vt = !0, this.bt = t);\n }\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */ Ct() {\n let t = Es(), e = Es(), n = Es();\n return this.Rt.forEach(((s, i) => {\n switch (i) {\n case 0 /* ChangeType.Added */ :\n t = t.add(s);\n break;\n\n case 2 /* ChangeType.Modified */ :\n e = e.add(s);\n break;\n\n case 1 /* ChangeType.Removed */ :\n n = n.add(s);\n break;\n\n default:\n O();\n }\n })), new Ps(this.bt, this.Pt, t, e, n);\n }\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */ xt() {\n this.vt = !1, this.Rt = Ns();\n }\n Nt(t, e) {\n this.vt = !0, this.Rt = this.Rt.insert(t, e);\n }\n kt(t) {\n this.vt = !0, this.Rt = this.Rt.remove(t);\n }\n Ot() {\n this.At += 1;\n }\n Mt() {\n this.At -= 1;\n }\n Ft() {\n this.vt = !0, this.Pt = !0;\n }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass Cs {\n constructor(t) {\n this.$t = t, \n /** The internal state of all tracked targets. */\n this.Bt = new Map, \n /** Keeps track of the documents to update since the last raised snapshot. */\n this.Lt = ds(), \n /** A mapping of document keys to their set of target IDs. */\n this.qt = xs(), \n /**\n * A list of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n this.Ut = new We(Z);\n }\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */ Kt(t) {\n for (const e of t.It) t.Tt && t.Tt.isFoundDocument() ? this.Gt(e, t.Tt) : this.Qt(e, t.key, t.Tt);\n for (const e of t.removedTargetIds) this.Qt(e, t.key, t.Tt);\n }\n /** Processes and adds the WatchTargetChange to the current set of changes. */ jt(t) {\n this.forEachTarget(t, (e => {\n const n = this.Wt(e);\n switch (t.state) {\n case 0 /* WatchTargetChangeState.NoChange */ :\n this.zt(e) && n.Dt(t.resumeToken);\n break;\n\n case 1 /* WatchTargetChangeState.Added */ :\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Mt(), n.Vt || \n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n n.xt(), n.Dt(t.resumeToken);\n break;\n\n case 2 /* WatchTargetChangeState.Removed */ :\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Mt(), n.Vt || this.removeTarget(e);\n break;\n\n case 3 /* WatchTargetChangeState.Current */ :\n this.zt(e) && (n.Ft(), n.Dt(t.resumeToken));\n break;\n\n case 4 /* WatchTargetChangeState.Reset */ :\n this.zt(e) && (\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.Ht(e), n.Dt(t.resumeToken));\n break;\n\n default:\n O();\n }\n }));\n }\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */ forEachTarget(t, e) {\n t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Bt.forEach(((t, n) => {\n this.zt(n) && e(n);\n }));\n }\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */ Jt(t) {\n const e = t.targetId, n = t.Et.count, s = this.Yt(e);\n if (s) {\n const t = s.target;\n if (rn(t)) if (0 === n) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const n = new ct(t.path);\n this.Qt(e, n, Ze.newNoDocument(n, st.min()));\n } else M(1 === n); else {\n this.Xt(e) !== n && (\n // Existence filter mismatch: We reset the mapping and raise a new\n // snapshot with `isFromCache:true`.\n this.Ht(e), this.Ut = this.Ut.add(e));\n }\n }\n }\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */ Zt(t) {\n const e = new Map;\n this.Bt.forEach(((n, s) => {\n const i = this.Yt(s);\n if (i) {\n if (n.current && rn(i.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const e = new ct(i.target.path);\n null !== this.Lt.get(e) || this.te(s, e) || this.Qt(s, e, Ze.newNoDocument(e, t));\n }\n n.St && (e.set(s, n.Ct()), n.xt());\n }\n }));\n let n = Es();\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n \n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.qt.forEach(((t, e) => {\n let s = !0;\n e.forEachWhile((t => {\n const e = this.Yt(t);\n return !e || 2 /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1, !1);\n })), s && (n = n.add(t));\n })), this.Lt.forEach(((e, n) => n.setReadTime(t)));\n const s = new bs(t, e, this.Ut, this.Lt, n);\n return this.Lt = ds(), this.qt = xs(), this.Ut = new We(Z), s;\n }\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n Gt(t, e) {\n if (!this.zt(t)) return;\n const n = this.te(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;\n this.Wt(t).Nt(e.key, n), this.Lt = this.Lt.insert(e.key, e), this.qt = this.qt.insert(e.key, this.ee(e.key).add(t));\n }\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n Qt(t, e, n) {\n if (!this.zt(t)) return;\n const s = this.Wt(t);\n this.te(t, e) ? s.Nt(e, 1 /* ChangeType.Removed */) : \n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n s.kt(e), this.qt = this.qt.insert(e, this.ee(e).delete(t)), n && (this.Lt = this.Lt.insert(e, n));\n }\n removeTarget(t) {\n this.Bt.delete(t);\n }\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */ Xt(t) {\n const e = this.Wt(t).Ct();\n return this.$t.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;\n }\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */ Ot(t) {\n this.Wt(t).Ot();\n }\n Wt(t) {\n let e = this.Bt.get(t);\n return e || (e = new Ds, this.Bt.set(t, e)), e;\n }\n ee(t) {\n let e = this.qt.get(t);\n return e || (e = new We(Z), this.qt = this.qt.insert(t, e)), e;\n }\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */ zt(t) {\n const e = null !== this.Yt(t);\n return e || C(\"WatchChangeAggregator\", \"Detected inactive target\", t), e;\n }\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */ Yt(t) {\n const e = this.Bt.get(t);\n return e && e.Vt ? null : this.$t.ne(t);\n }\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */ Ht(t) {\n this.Bt.set(t, new Ds);\n this.$t.getRemoteKeysForTarget(t).forEach((e => {\n this.Qt(t, e, /*updatedDocument=*/ null);\n }));\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */ te(t, e) {\n return this.$t.getRemoteKeysForTarget(t).has(e);\n }\n}\n\nfunction xs() {\n return new Ge(ct.comparator);\n}\n\nfunction Ns() {\n return new Ge(ct.comparator);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ks = (() => {\n const t = {\n asc: \"ASCENDING\",\n desc: \"DESCENDING\"\n };\n return t;\n})(), Os = (() => {\n const t = {\n \"<\": \"LESS_THAN\",\n \"<=\": \"LESS_THAN_OR_EQUAL\",\n \">\": \"GREATER_THAN\",\n \">=\": \"GREATER_THAN_OR_EQUAL\",\n \"==\": \"EQUAL\",\n \"!=\": \"NOT_EQUAL\",\n \"array-contains\": \"ARRAY_CONTAINS\",\n in: \"IN\",\n \"not-in\": \"NOT_IN\",\n \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n };\n return t;\n})(), Ms = (() => {\n const t = {\n and: \"AND\",\n or: \"OR\"\n };\n return t;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass Fs {\n constructor(t, e) {\n this.databaseId = t, this.wt = e;\n }\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction $s(t, e) {\n if (t.wt) {\n return `${new Date(1e3 * e.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + e.nanoseconds).slice(-9)}Z`;\n }\n return {\n seconds: \"\" + e.seconds,\n nanos: e.nanoseconds\n };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction Bs(t, e) {\n return t.wt ? e.toBase64() : e.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function Ls(t, e) {\n return $s(t, e.toTimestamp());\n}\n\nfunction qs(t) {\n return M(!!t), st.fromTimestamp(function(t) {\n const e = Wt(t);\n return new nt(e.seconds, e.nanos);\n }(t));\n}\n\nfunction Us(t, e) {\n return function(t) {\n return new rt([ \"projects\", t.projectId, \"databases\", t.database ]);\n }(t).child(\"documents\").child(e).canonicalString();\n}\n\nfunction Ks(t) {\n const e = rt.fromString(t);\n return M(wi(e)), e;\n}\n\nfunction Gs(t, e) {\n return Us(t.databaseId, e.path);\n}\n\nfunction Qs(t, e) {\n const n = Ks(e);\n if (n.get(1) !== t.databaseId.projectId) throw new L(B.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + t.databaseId.projectId);\n if (n.get(3) !== t.databaseId.database) throw new L(B.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + t.databaseId.database);\n return new ct(Hs(n));\n}\n\nfunction js(t, e) {\n return Us(t.databaseId, e);\n}\n\nfunction Ws(t) {\n const e = Ks(t);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n return 4 === e.length ? rt.emptyPath() : Hs(e);\n}\n\nfunction zs(t) {\n return new rt([ \"projects\", t.databaseId.projectId, \"databases\", t.databaseId.database ]).canonicalString();\n}\n\nfunction Hs(t) {\n return M(t.length > 4 && \"documents\" === t.get(4)), t.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function Js(t, e, n) {\n return {\n name: Gs(t, e),\n fields: n.value.mapValue.fields\n };\n}\n\nfunction Ys(t, e, n) {\n const s = Qs(t, e.name), i = qs(e.updateTime), r = e.createTime ? qs(e.createTime) : st.min(), o = new Ye({\n mapValue: {\n fields: e.fields\n }\n }), u = Ze.newFoundDocument(s, i, r, o);\n return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;\n}\n\nfunction Xs(t, e) {\n return \"found\" in e ? function(t, e) {\n M(!!e.found), e.found.name, e.found.updateTime;\n const n = Qs(t, e.found.name), s = qs(e.found.updateTime), i = e.found.createTime ? qs(e.found.createTime) : st.min(), r = new Ye({\n mapValue: {\n fields: e.found.fields\n }\n });\n return Ze.newFoundDocument(n, s, i, r);\n }(t, e) : \"missing\" in e ? function(t, e) {\n M(!!e.missing), M(!!e.readTime);\n const n = Qs(t, e.missing), s = qs(e.readTime);\n return Ze.newNoDocument(n, s);\n }(t, e) : O();\n}\n\nfunction Zs(t, e) {\n let n;\n if (\"targetChange\" in e) {\n e.targetChange;\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const s = function(t) {\n return \"NO_CHANGE\" === t ? 0 /* WatchTargetChangeState.NoChange */ : \"ADD\" === t ? 1 /* WatchTargetChangeState.Added */ : \"REMOVE\" === t ? 2 /* WatchTargetChangeState.Removed */ : \"CURRENT\" === t ? 3 /* WatchTargetChangeState.Current */ : \"RESET\" === t ? 4 /* WatchTargetChangeState.Reset */ : O();\n }(e.targetChange.targetChangeType || \"NO_CHANGE\"), i = e.targetChange.targetIds || [], r = function(t, e) {\n return t.wt ? (M(void 0 === e || \"string\" == typeof e), Qt.fromBase64String(e || \"\")) : (M(void 0 === e || e instanceof Uint8Array), \n Qt.fromUint8Array(e || new Uint8Array));\n }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {\n const e = void 0 === t.code ? B.UNKNOWN : hs(t.code);\n return new L(e, t.message || \"\");\n }\n /**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */ (o);\n n = new Ss(s, i, r, u || null);\n } else if (\"documentChange\" in e) {\n e.documentChange;\n const s = e.documentChange;\n s.document, s.document.name, s.document.updateTime;\n const i = Qs(t, s.document.name), r = qs(s.document.updateTime), o = s.document.createTime ? qs(s.document.createTime) : st.min(), u = new Ye({\n mapValue: {\n fields: s.document.fields\n }\n }), c = Ze.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];\n n = new vs(a, h, c.key, c);\n } else if (\"documentDelete\" in e) {\n e.documentDelete;\n const s = e.documentDelete;\n s.document;\n const i = Qs(t, s.document), r = s.readTime ? qs(s.readTime) : st.min(), o = Ze.newNoDocument(i, r), u = s.removedTargetIds || [];\n n = new vs([], u, o.key, o);\n } else if (\"documentRemove\" in e) {\n e.documentRemove;\n const s = e.documentRemove;\n s.document;\n const i = Qs(t, s.document), r = s.removedTargetIds || [];\n n = new vs([], r, i, null);\n } else {\n if (!(\"filter\" in e)) return O();\n {\n e.filter;\n const t = e.filter;\n t.targetId;\n const s = t.count || 0, i = new os(s), r = t.targetId;\n n = new Vs(r, i);\n }\n }\n return n;\n}\n\nfunction ti(t, e) {\n let n;\n if (e instanceof Zn) n = {\n update: Js(t, e.key, e.value)\n }; else if (e instanceof is) n = {\n delete: Gs(t, e.key)\n }; else if (e instanceof ts) n = {\n update: Js(t, e.key, e.data),\n updateMask: _i(e.fieldMask)\n }; else {\n if (!(e instanceof rs)) return O();\n n = {\n verify: Gs(t, e.key)\n };\n }\n return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {\n const n = e.transform;\n if (n instanceof kn) return {\n fieldPath: e.field.canonicalString(),\n setToServerValue: \"REQUEST_TIME\"\n };\n if (n instanceof On) return {\n fieldPath: e.field.canonicalString(),\n appendMissingElements: {\n values: n.elements\n }\n };\n if (n instanceof Fn) return {\n fieldPath: e.field.canonicalString(),\n removeAllFromArray: {\n values: n.elements\n }\n };\n if (n instanceof Bn) return {\n fieldPath: e.field.canonicalString(),\n increment: n.gt\n };\n throw O();\n }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {\n return void 0 !== e.updateTime ? {\n updateTime: Ls(t, e.updateTime)\n } : void 0 !== e.exists ? {\n exists: e.exists\n } : O();\n }(t, e.precondition)), n;\n}\n\nfunction ei(t, e) {\n const n = e.currentDocument ? function(t) {\n return void 0 !== t.updateTime ? Qn.updateTime(qs(t.updateTime)) : void 0 !== t.exists ? Qn.exists(t.exists) : Qn.none();\n }(e.currentDocument) : Qn.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {\n let n = null;\n if (\"setToServerValue\" in e) M(\"REQUEST_TIME\" === e.setToServerValue), n = new kn; else if (\"appendMissingElements\" in e) {\n const t = e.appendMissingElements.values || [];\n n = new On(t);\n } else if (\"removeAllFromArray\" in e) {\n const t = e.removeAllFromArray.values || [];\n n = new Fn(t);\n } else \"increment\" in e ? n = new Bn(t, e.increment) : O();\n const s = ut.fromServerFormat(e.fieldPath);\n return new Un(s, n);\n }(t, e))) : [];\n if (e.update) {\n e.update.name;\n const i = Qs(t, e.update.name), r = new Ye({\n mapValue: {\n fields: e.update.fields\n }\n });\n if (e.updateMask) {\n const t = function(t) {\n const e = t.fieldPaths || [];\n return new Je(e.map((t => ut.fromServerFormat(t))));\n }(e.updateMask);\n return new ts(i, r, t, n, s);\n }\n return new Zn(i, r, n, s);\n }\n if (e.delete) {\n const s = Qs(t, e.delete);\n return new is(s, n);\n }\n if (e.verify) {\n const s = Qs(t, e.verify);\n return new rs(s, n);\n }\n return O();\n}\n\nfunction ni(t, e) {\n return t && t.length > 0 ? (M(void 0 !== e), t.map((t => function(t, e) {\n // NOTE: Deletes don't have an updateTime.\n let n = t.updateTime ? qs(t.updateTime) : qs(e);\n return n.isEqual(st.min()) && (\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n n = qs(e)), new Gn(n, t.transformResults || []);\n }(t, e)))) : [];\n}\n\nfunction si(t, e) {\n return {\n documents: [ js(t, e.path) ]\n };\n}\n\nfunction ii(t, e) {\n // Dissect the path into parent, collectionId, and optional key filter.\n const n = {\n structuredQuery: {}\n }, s = e.path;\n null !== e.collectionGroup ? (n.parent = js(t, s), n.structuredQuery.from = [ {\n collectionId: e.collectionGroup,\n allDescendants: !0\n } ]) : (n.parent = js(t, s.popLast()), n.structuredQuery.from = [ {\n collectionId: s.lastSegment()\n } ]);\n const i = function(t) {\n if (0 === t.length) return;\n return di(be.create(t, \"and\" /* CompositeOperator.AND */));\n }(e.filters);\n i && (n.structuredQuery.where = i);\n const r = function(t) {\n if (0 === t.length) return;\n return t.map((t => \n // visible for testing\n function(t) {\n return {\n field: li(t.field),\n direction: ci(t.dir)\n };\n }(t)));\n }(e.orderBy);\n r && (n.structuredQuery.orderBy = r);\n const o = function(t, e) {\n return t.wt || qt(e) ? e : {\n value: e\n };\n }\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */ (t, e.limit);\n var u;\n return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {\n before: (u = e.startAt).inclusive,\n values: u.position\n }), e.endAt && (n.structuredQuery.endAt = function(t) {\n return {\n before: !t.inclusive,\n values: t.position\n };\n }(e.endAt)), n;\n}\n\nfunction ri(t) {\n let e = Ws(t.parent);\n const n = t.structuredQuery, s = n.from ? n.from.length : 0;\n let i = null;\n if (s > 0) {\n M(1 === s);\n const t = n.from[0];\n t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);\n }\n let r = [];\n n.where && (r = function(t) {\n const e = ui(t);\n if (e instanceof be && Ve(e)) return e.getFilters();\n return [ e ];\n }(n.where));\n let o = [];\n n.orderBy && (o = n.orderBy.map((t => function(t) {\n return new Ue(fi(t.field), \n // visible for testing\n function(t) {\n switch (t) {\n case \"ASCENDING\":\n return \"asc\" /* Direction.ASCENDING */;\n\n case \"DESCENDING\":\n return \"desc\" /* Direction.DESCENDING */;\n\n default:\n return;\n }\n }\n // visible for testing\n (t.direction));\n }\n // visible for testing\n (t))));\n let u = null;\n n.limit && (u = function(t) {\n let e;\n return e = \"object\" == typeof t ? t.value : t, qt(e) ? null : e;\n }(n.limit));\n let c = null;\n n.startAt && (c = function(t) {\n const e = !!t.before, n = t.values || [];\n return new Ie(n, e);\n }(n.startAt));\n let a = null;\n return n.endAt && (a = function(t) {\n const e = !t.before, n = t.values || [];\n return new Ie(n, e);\n }\n // visible for testing\n (n.endAt)), hn(e, i, o, r, u, \"F\" /* LimitType.First */ , c, a);\n}\n\nfunction oi(t, e) {\n const n = function(t, e) {\n switch (e) {\n case 0 /* TargetPurpose.Listen */ :\n return null;\n\n case 1 /* TargetPurpose.ExistenceFilterMismatch */ :\n return \"existence-filter-mismatch\";\n\n case 2 /* TargetPurpose.LimboResolution */ :\n return \"limbo-document\";\n\n default:\n return O();\n }\n }(0, e.purpose);\n return null == n ? null : {\n \"goog-listen-tags\": n\n };\n}\n\nfunction ui(t) {\n return void 0 !== t.unaryFilter ? function(t) {\n switch (t.unaryFilter.op) {\n case \"IS_NAN\":\n const e = fi(t.unaryFilter.field);\n return Re.create(e, \"==\" /* Operator.EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NULL\":\n const n = fi(t.unaryFilter.field);\n return Re.create(n, \"==\" /* Operator.EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n case \"IS_NOT_NAN\":\n const s = fi(t.unaryFilter.field);\n return Re.create(s, \"!=\" /* Operator.NOT_EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NOT_NULL\":\n const i = fi(t.unaryFilter.field);\n return Re.create(i, \"!=\" /* Operator.NOT_EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n default:\n return O();\n }\n }(t) : void 0 !== t.fieldFilter ? function(t) {\n return Re.create(fi(t.fieldFilter.field), function(t) {\n switch (t) {\n case \"EQUAL\":\n return \"==\" /* Operator.EQUAL */;\n\n case \"NOT_EQUAL\":\n return \"!=\" /* Operator.NOT_EQUAL */;\n\n case \"GREATER_THAN\":\n return \">\" /* Operator.GREATER_THAN */;\n\n case \"GREATER_THAN_OR_EQUAL\":\n return \">=\" /* Operator.GREATER_THAN_OR_EQUAL */;\n\n case \"LESS_THAN\":\n return \"<\" /* Operator.LESS_THAN */;\n\n case \"LESS_THAN_OR_EQUAL\":\n return \"<=\" /* Operator.LESS_THAN_OR_EQUAL */;\n\n case \"ARRAY_CONTAINS\":\n return \"array-contains\" /* Operator.ARRAY_CONTAINS */;\n\n case \"IN\":\n return \"in\" /* Operator.IN */;\n\n case \"NOT_IN\":\n return \"not-in\" /* Operator.NOT_IN */;\n\n case \"ARRAY_CONTAINS_ANY\":\n return \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */;\n\n default:\n return O();\n }\n }(t.fieldFilter.op), t.fieldFilter.value);\n }(t) : void 0 !== t.compositeFilter ? function(t) {\n return be.create(t.compositeFilter.filters.map((t => ui(t))), function(t) {\n switch (t) {\n case \"AND\":\n return \"and\" /* CompositeOperator.AND */;\n\n case \"OR\":\n return \"or\" /* CompositeOperator.OR */;\n\n default:\n return O();\n }\n }(t.compositeFilter.op));\n }(t) : O();\n}\n\nfunction ci(t) {\n return ks[t];\n}\n\nfunction ai(t) {\n return Os[t];\n}\n\nfunction hi(t) {\n return Ms[t];\n}\n\nfunction li(t) {\n return {\n fieldPath: t.canonicalString()\n };\n}\n\nfunction fi(t) {\n return ut.fromServerFormat(t.fieldPath);\n}\n\nfunction di(t) {\n return t instanceof Re ? function(t) {\n if (\"==\" /* Operator.EQUAL */ === t.op) {\n if (fe(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NAN\"\n }\n };\n if (le(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NULL\"\n }\n };\n } else if (\"!=\" /* Operator.NOT_EQUAL */ === t.op) {\n if (fe(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NOT_NAN\"\n }\n };\n if (le(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NOT_NULL\"\n }\n };\n }\n return {\n fieldFilter: {\n field: li(t.field),\n op: ai(t.op),\n value: t.value\n }\n };\n }(t) : t instanceof be ? function(t) {\n const e = t.getFilters().map((t => di(t)));\n if (1 === e.length) return e[0];\n return {\n compositeFilter: {\n op: hi(t.op),\n filters: e\n }\n };\n }(t) : O();\n}\n\nfunction _i(t) {\n const e = [];\n return t.fields.forEach((t => e.push(t.canonicalString()))), {\n fieldPaths: e\n };\n}\n\nfunction wi(t) {\n // Resource names have at least 4 components (project ID, database ID)\n return t.length >= 4 && \"projects\" === t.get(0) && \"databases\" === t.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction mi(t) {\n let e = \"\";\n for (let n = 0; n < t.length; n++) e.length > 0 && (e = yi(e)), e = gi(t.get(n), e);\n return yi(e);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function gi(t, e) {\n let n = e;\n const s = t.length;\n for (let e = 0; e < s; e++) {\n const s = t.charAt(e);\n switch (s) {\n case \"\\0\":\n n += \"\u0001\u0010\";\n break;\n\n case \"\u0001\":\n n += \"\u0001\u0011\";\n break;\n\n default:\n n += s;\n }\n }\n return n;\n}\n\n/** Encodes a path separator into the given result */ function yi(t) {\n return t + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function pi(t) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const e = t.length;\n if (M(e >= 2), 2 === e) return M(\"\u0001\" === t.charAt(0) && \"\u0001\" === t.charAt(1)), rt.emptyPath();\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const n = e - 2, s = [];\n let i = \"\";\n for (let r = 0; r < e; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const e = t.indexOf(\"\u0001\", r);\n (e < 0 || e > n) && O();\n switch (t.charAt(e + 1)) {\n case \"\u0001\":\n const n = t.substring(r, e);\n let o;\n 0 === i.length ? \n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n o = n : (i += n, o = i, i = \"\"), s.push(o);\n break;\n\n case \"\u0010\":\n i += t.substring(r, e), i += \"\\0\";\n break;\n\n case \"\u0011\":\n // The escape character can be used in the output to encode itself.\n i += t.substring(r, e + 1);\n break;\n\n default:\n O();\n }\n r = e + 2;\n }\n return new rt(s);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ii = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction Ti(t, e) {\n return [ t, mi(e) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function Ei(t, e, n) {\n return [ t, mi(e), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const Ai = {}, Ri = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], bi = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], Pi = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], vi = [ \"canonicalId\", \"targetId\" ], Vi = [ \"targetId\", \"path\" ], Si = [ \"path\", \"targetId\" ], Di = [ \"collectionId\", \"parent\" ], Ci = [ \"indexId\", \"uid\" ], xi = [ \"uid\", \"sequenceNumber\" ], Ni = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], ki = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], Oi = [ \"userId\", \"collectionPath\", \"documentId\" ], Mi = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], Fi = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], $i = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], Bi = [ ...$i, \"documentOverlays\" ], Li = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], qi = Li, Ui = [ ...qi, \"indexConfiguration\", \"indexState\", \"indexEntries\" ];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Ki extends Tt {\n constructor(t, e) {\n super(), this.se = t, this.currentSequenceNumber = e;\n }\n}\n\nfunction Gi(t, e) {\n const n = $(t);\n return bt.M(n.se, e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class Qi {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(t, e, n, s) {\n this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */ applyToRemoteDocument(t, e) {\n const n = e.mutationResults;\n for (let e = 0; e < this.mutations.length; e++) {\n const s = this.mutations[e];\n if (s.key.isEqual(t.key)) {\n Hn(s, t, n[e]);\n }\n }\n }\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */ applyToLocalView(t, e) {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Jn(n, t, e, this.localWriteTime));\n // Second, apply all user-provided mutations.\n for (const n of this.mutations) n.key.isEqual(t.key) && (e = Jn(n, t, e, this.localWriteTime));\n return e;\n }\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */ applyToLocalDocumentSet(t, e) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const n = ys();\n return this.mutations.forEach((s => {\n const i = t.get(s.key), r = i.overlayedDocument;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n let o = this.applyToLocalView(r, i.mutatedFields);\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n o = e.has(s.key) ? null : o;\n const u = zn(r, o);\n null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(st.min());\n })), n;\n }\n keys() {\n return this.mutations.reduce(((t, e) => t.add(e.key)), Es());\n }\n isEqual(t) {\n return this.batchId === t.batchId && tt(this.mutations, t.mutations, ((t, e) => Xn(t, e))) && tt(this.baseMutations, t.baseMutations, ((t, e) => Xn(t, e)));\n }\n}\n\n/** The result of applying a mutation batch to the backend. */ class ji {\n constructor(t, e, n, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n s) {\n this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=&gt;version mapping (docVersions).\n */ static from(t, e, n) {\n M(t.mutations.length === n.length);\n let s = Is;\n const i = t.mutations;\n for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);\n return new ji(t, e, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class Wi {\n constructor(t, e) {\n this.largestBatchId = t, this.mutation = e;\n }\n getKey() {\n return this.mutation.key;\n }\n isEqual(t) {\n return null !== t && this.mutation === t.mutation;\n }\n toString() {\n return `Overlay{\\n largestBatchId: ${this.largestBatchId},\\n mutation: ${this.mutation.toString()}\\n }`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class zi {\n constructor(\n /** The target being listened to. */\n t, \n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n e, \n /** The purpose of the target. */\n n, \n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n s, \n /** The latest snapshot version seen for this target. */\n i = st.min()\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */ , r = st.min()\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */ , o = Qt.EMPTY_BYTE_STRING) {\n this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i, \n this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;\n }\n /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {\n return new zi(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);\n }\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */ withResumeToken(t, e) {\n return new zi(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);\n }\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */ withLastLimboFreeSnapshotVersion(t) {\n return new zi(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class Hi {\n constructor(t) {\n this.ie = t;\n }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function Ji(t, e) {\n let n;\n if (e.document) n = Ys(t.ie, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {\n const t = ct.fromSegments(e.noDocument.path), s = tr(e.noDocument.readTime);\n n = Ze.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();\n } else {\n if (!e.unknownDocument) return O();\n {\n const t = ct.fromSegments(e.unknownDocument.path), s = tr(e.unknownDocument.version);\n n = Ze.newUnknownDocument(t, s);\n }\n }\n return e.readTime && n.setReadTime(function(t) {\n const e = new nt(t[0], t[1]);\n return st.fromTimestamp(e);\n }(e.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function Yi(t, e) {\n const n = e.key, s = {\n prefixPath: n.getCollectionPath().popLast().toArray(),\n collectionGroup: n.collectionGroup,\n documentId: n.path.lastSegment(),\n readTime: Xi(e.readTime),\n hasCommittedMutations: e.hasCommittedMutations\n };\n if (e.isFoundDocument()) s.document = function(t, e) {\n return {\n name: Gs(t, e.key),\n fields: e.data.value.mapValue.fields,\n updateTime: $s(t, e.version.toTimestamp()),\n createTime: $s(t, e.createTime.toTimestamp())\n };\n }(t.ie, e); else if (e.isNoDocument()) s.noDocument = {\n path: n.path.toArray(),\n readTime: Zi(e.version)\n }; else {\n if (!e.isUnknownDocument()) return O();\n s.unknownDocument = {\n path: n.path.toArray(),\n version: Zi(e.version)\n };\n }\n return s;\n}\n\nfunction Xi(t) {\n const e = t.toTimestamp();\n return [ e.seconds, e.nanoseconds ];\n}\n\nfunction Zi(t) {\n const e = t.toTimestamp();\n return {\n seconds: e.seconds,\n nanoseconds: e.nanoseconds\n };\n}\n\nfunction tr(t) {\n const e = new nt(t.seconds, t.nanoseconds);\n return st.fromTimestamp(e);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction er(t, e) {\n const n = (e.baseMutations || []).map((e => ei(t.ie, e)));\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let t = 0; t < e.mutations.length - 1; ++t) {\n const n = e.mutations[t];\n if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {\n const s = e.mutations[t + 1];\n n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1), \n ++t;\n }\n }\n const s = e.mutations.map((e => ei(t.ie, e))), i = nt.fromMillis(e.localWriteTimeMs);\n return new Qi(e.batchId, i, n, s);\n}\n\n/** Decodes a DbTarget into TargetData */ function nr(t) {\n const e = tr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? tr(t.lastLimboFreeSnapshotVersion) : st.min();\n let s;\n var i;\n return void 0 !== t.query.documents ? (M(1 === (i = t.query).documents.length), \n s = gn(ln(Ws(i.documents[0])))) : s = function(t) {\n return gn(ri(t));\n }(t.query), new zi(s, t.targetId, 0 /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Qt.fromBase64String(t.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function sr(t, e) {\n const n = Zi(e.snapshotVersion), s = Zi(e.lastLimboFreeSnapshotVersion);\n let i;\n i = rn(e.target) ? si(t.ie, e.target) : ii(t.ie, e.target);\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const r = e.resumeToken.toBase64();\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: e.targetId,\n canonicalId: nn(e.target),\n readTime: n,\n resumeToken: r,\n lastListenSequenceNumber: e.sequenceNumber,\n lastLimboFreeSnapshotVersion: s,\n query: i\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction ir(t) {\n const e = ri({\n parent: t.parent,\n structuredQuery: t.structuredQuery\n });\n return \"LAST\" === t.limitType ? pn(e, e.limit, \"L\" /* LimitType.Last */) : e;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction rr(t, e) {\n return new Wi(e.largestBatchId, ei(t.ie, e.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction or(t, e) {\n const n = e.path.lastSegment();\n return [ t, mi(e.path.popLast()), n ];\n}\n\nfunction ur(t, e, n, s) {\n return {\n indexId: t,\n uid: e.uid || \"\",\n sequenceNumber: n,\n readTime: Zi(s.readTime),\n documentKey: mi(s.documentKey.path),\n largestBatchId: s.largestBatchId\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class cr {\n getBundleMetadata(t, e) {\n return ar(t).get(e).next((t => {\n if (t) return {\n id: (e = t).bundleId,\n createTime: tr(e.createTime),\n version: e.version\n };\n /** Encodes a DbBundle to a BundleMetadata object. */\n var e;\n /** Encodes a BundleMetadata to a DbBundle. */ }));\n }\n saveBundleMetadata(t, e) {\n return ar(t).put({\n bundleId: (n = e).id,\n createTime: Zi(qs(n.createTime)),\n version: n.version\n });\n var n;\n /** Encodes a DbNamedQuery to a NamedQuery. */ }\n getNamedQuery(t, e) {\n return hr(t).get(e).next((t => {\n if (t) return {\n name: (e = t).name,\n query: ir(e.bundledQuery),\n readTime: tr(e.readTime)\n };\n var e;\n /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));\n }\n saveNamedQuery(t, e) {\n return hr(t).put(function(t) {\n return {\n name: t.name,\n readTime: Zi(qs(t.readTime)),\n bundledQuery: t.bundledQuery\n };\n }(e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function ar(t) {\n return Gi(t, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function hr(t) {\n return Gi(t, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class lr {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(t, e) {\n this.yt = t, this.userId = e;\n }\n static re(t, e) {\n const n = e.uid || \"\";\n return new lr(t, n);\n }\n getOverlay(t, e) {\n return fr(t).get(or(this.userId, e)).next((t => t ? rr(this.yt, t) : null));\n }\n getOverlays(t, e) {\n const n = gs();\n return At.forEach(e, (e => this.getOverlay(t, e).next((t => {\n null !== t && n.set(e, t);\n })))).next((() => n));\n }\n saveOverlays(t, e, n) {\n const s = [];\n return n.forEach(((n, i) => {\n const r = new Wi(e, i);\n s.push(this.oe(t, r));\n })), At.waitFor(s);\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = new Set;\n // Get the set of unique collection paths.\n e.forEach((t => s.add(mi(t.getCollectionPath()))));\n const i = [];\n return s.forEach((e => {\n const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n i.push(fr(t).Y(\"collectionPathOverlayIndex\", s));\n })), At.waitFor(i);\n }\n getOverlaysForCollection(t, e, n) {\n const s = gs(), i = mi(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return fr(t).W(\"collectionPathOverlayIndex\", r).next((t => {\n for (const e of t) {\n const t = rr(this.yt, e);\n s.set(t.getKey(), t);\n }\n return s;\n }));\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n const i = gs();\n let r;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return fr(t).Z({\n index: \"collectionGroupOverlayIndex\",\n range: o\n }, ((t, e, n) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const o = rr(this.yt, e);\n i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();\n })).next((() => i));\n }\n oe(t, e) {\n return fr(t).put(function(t, e, n) {\n const [s, i, r] = or(e, n.mutation.key);\n return {\n userId: e,\n collectionPath: i,\n documentId: r,\n collectionGroup: n.mutation.key.getCollectionGroup(),\n largestBatchId: n.largestBatchId,\n overlayMutation: ti(t.ie, n.mutation)\n };\n }(this.yt, this.userId, e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function fr(t) {\n return Gi(t, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer. */\nclass dr {\n constructor() {}\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n // As an example, consider the resulting encoding for:\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n /** Writes an index value. */\n ue(t, e) {\n this.ce(t, e), \n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n e.ae();\n }\n ce(t, e) {\n if (\"nullValue\" in t) this.he(e, 5); else if (\"booleanValue\" in t) this.he(e, 10), \n e.le(t.booleanValue ? 1 : 0); else if (\"integerValue\" in t) this.he(e, 15), e.le(zt(t.integerValue)); else if (\"doubleValue\" in t) {\n const n = zt(t.doubleValue);\n isNaN(n) ? this.he(e, 13) : (this.he(e, 15), Ut(n) ? \n // -0.0, 0 and 0.0 are all considered the same\n e.le(0) : e.le(n));\n } else if (\"timestampValue\" in t) {\n const n = t.timestampValue;\n this.he(e, 20), \"string\" == typeof n ? e.fe(n) : (e.fe(`${n.seconds || \"\"}`), e.le(n.nanos || 0));\n } else if (\"stringValue\" in t) this.de(t.stringValue, e), this._e(e); else if (\"bytesValue\" in t) this.he(e, 30), \n e.we(Ht(t.bytesValue)), this._e(e); else if (\"referenceValue\" in t) this.me(t.referenceValue, e); else if (\"geoPointValue\" in t) {\n const n = t.geoPointValue;\n this.he(e, 45), e.le(n.latitude || 0), e.le(n.longitude || 0);\n } else \"mapValue\" in t ? we(t) ? this.he(e, Number.MAX_SAFE_INTEGER) : (this.ge(t.mapValue, e), \n this._e(e)) : \"arrayValue\" in t ? (this.ye(t.arrayValue, e), this._e(e)) : O();\n }\n de(t, e) {\n this.he(e, 25), this.pe(t, e);\n }\n pe(t, e) {\n e.fe(t);\n }\n ge(t, e) {\n const n = t.fields || {};\n this.he(e, 55);\n for (const t of Object.keys(n)) this.de(t, e), this.ce(n[t], e);\n }\n ye(t, e) {\n const n = t.values || [];\n this.he(e, 50);\n for (const t of n) this.ce(t, e);\n }\n me(t, e) {\n this.he(e, 37);\n ct.fromName(t).path.forEach((t => {\n this.he(e, 60), this.pe(t, e);\n }));\n }\n he(t, e) {\n t.le(e);\n }\n _e(t) {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n t.le(2);\n }\n}\n\ndr.Ie = new dr;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction _r(t) {\n if (0 === t) return 8;\n let e = 0;\n return t >> 4 == 0 && (\n // Test if the first four bits are zero.\n e += 4, t <<= 4), t >> 6 == 0 && (\n // Test if the first two (or next two) bits are zero.\n e += 2, t <<= 2), t >> 7 == 0 && (\n // Test if the remaining bit is zero.\n e += 1), e;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction wr(t) {\n // This is just the number of bytes for the unsigned representation of the number.\n const e = 64 - function(t) {\n let e = 0;\n for (let n = 0; n < 8; ++n) {\n const s = _r(255 & t[n]);\n if (e += s, 8 !== s) break;\n }\n return e;\n }(t);\n return Math.ceil(e / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class mr {\n constructor() {\n this.buffer = new Uint8Array(1024), this.position = 0;\n }\n Te(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.Ee(n.value), n = e.next();\n this.Ae();\n }\n Re(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.be(n.value), n = e.next();\n this.Pe();\n }\n /** Writes utf8 bytes into this byte sequence, ascending. */ ve(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.Ee(t); else if (t < 2048) this.Ee(960 | t >>> 6), this.Ee(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.Ee(480 | t >>> 12), \n this.Ee(128 | 63 & t >>> 6), this.Ee(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.Ee(240 | t >>> 18), this.Ee(128 | 63 & t >>> 12), this.Ee(128 | 63 & t >>> 6), \n this.Ee(128 | 63 & t);\n }\n }\n this.Ae();\n }\n /** Writes utf8 bytes into this byte sequence, descending */ Ve(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.be(t); else if (t < 2048) this.be(960 | t >>> 6), this.be(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.be(480 | t >>> 12), \n this.be(128 | 63 & t >>> 6), this.be(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.be(240 | t >>> 18), this.be(128 | 63 & t >>> 12), this.be(128 | 63 & t >>> 6), \n this.be(128 | 63 & t);\n }\n }\n this.Pe();\n }\n Se(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const e = this.De(t), n = wr(e);\n this.Ce(1 + n), this.buffer[this.position++] = 255 & n;\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];\n }\n xe(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const e = this.De(t), n = wr(e);\n this.Ce(1 + n), this.buffer[this.position++] = ~(255 & n);\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */ Ne() {\n this.ke(255), this.ke(255);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */ Oe() {\n this.Me(255), this.Me(255);\n }\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */ reset() {\n this.position = 0;\n }\n seed(t) {\n this.Ce(t.length), this.buffer.set(t, this.position), this.position += t.length;\n }\n /** Makes a copy of the encoded bytes in this buffer. */ Fe() {\n return this.buffer.slice(0, this.position);\n }\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */ De(t) {\n const e = \n /** Converts a JavaScript number to a byte array (using big endian encoding). */\n function(t) {\n const e = new DataView(new ArrayBuffer(8));\n return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);\n }(t), n = 0 != (128 & e[0]);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n // Revert the two complement to get natural ordering\n e[0] ^= n ? 255 : 128;\n for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;\n return e;\n }\n /** Writes a single byte ascending to the buffer. */ Ee(t) {\n const e = 255 & t;\n 0 === e ? (this.ke(0), this.ke(255)) : 255 === e ? (this.ke(255), this.ke(0)) : this.ke(e);\n }\n /** Writes a single byte descending to the buffer. */ be(t) {\n const e = 255 & t;\n 0 === e ? (this.Me(0), this.Me(255)) : 255 === e ? (this.Me(255), this.Me(0)) : this.Me(t);\n }\n Ae() {\n this.ke(0), this.ke(1);\n }\n Pe() {\n this.Me(0), this.Me(1);\n }\n ke(t) {\n this.Ce(1), this.buffer[this.position++] = t;\n }\n Me(t) {\n this.Ce(1), this.buffer[this.position++] = ~t;\n }\n Ce(t) {\n const e = t + this.position;\n if (e <= this.buffer.length) return;\n // Try doubling.\n let n = 2 * this.buffer.length;\n // Still not big enough? Just allocate the right size.\n n < e && (n = e);\n // Create the new buffer.\n const s = new Uint8Array(n);\n s.set(this.buffer), // copy old data\n this.buffer = s;\n }\n}\n\nclass gr {\n constructor(t) {\n this.$e = t;\n }\n we(t) {\n this.$e.Te(t);\n }\n fe(t) {\n this.$e.ve(t);\n }\n le(t) {\n this.$e.Se(t);\n }\n ae() {\n this.$e.Ne();\n }\n}\n\nclass yr {\n constructor(t) {\n this.$e = t;\n }\n we(t) {\n this.$e.Re(t);\n }\n fe(t) {\n this.$e.Ve(t);\n }\n le(t) {\n this.$e.xe(t);\n }\n ae() {\n this.$e.Oe();\n }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class pr {\n constructor() {\n this.$e = new mr, this.Be = new gr(this.$e), this.Le = new yr(this.$e);\n }\n seed(t) {\n this.$e.seed(t);\n }\n qe(t) {\n return 0 /* IndexKind.ASCENDING */ === t ? this.Be : this.Le;\n }\n Fe() {\n return this.$e.Fe();\n }\n reset() {\n this.$e.reset();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class Ir {\n constructor(t, e, n, s) {\n this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;\n }\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */ Ue() {\n const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);\n return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n new Ir(this.indexId, this.documentKey, this.arrayValue, n);\n }\n}\n\nfunction Tr(t, e) {\n let n = t.indexId - e.indexId;\n return 0 !== n ? n : (n = Er(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = Er(t.directionalValue, e.directionalValue), \n 0 !== n ? n : ct.comparator(t.documentKey, e.documentKey)));\n}\n\nfunction Er(t, e) {\n for (let n = 0; n < t.length && n < e.length; ++n) {\n const s = t[n] - e[n];\n if (0 !== s) return s;\n }\n return t.length - e.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */ class Ar {\n constructor(t) {\n this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(), \n this.Ke = t.orderBy, this.Ge = [];\n for (const e of t.filters) {\n const t = e;\n t.isInequality() ? this.Qe = t : this.Ge.push(t);\n }\n }\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */ je(t) {\n M(t.collectionGroup === this.collectionId);\n // If there is an array element, find a matching filter.\n const e = ht(t);\n if (void 0 !== e && !this.We(e)) return !1;\n const n = lt(t);\n let s = 0, i = 0;\n // Process all equalities first. Equalities can appear out of order.\n for (;s < n.length && this.We(n[s]); ++s) ;\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (s === n.length) return !0;\n // If there is an inequality filter, the next segment must match both the\n // filter and the first orderBy clause.\n if (void 0 !== this.Qe) {\n const t = n[s];\n if (!this.ze(this.Qe, t) || !this.He(this.Ke[i++], t)) return !1;\n ++s;\n }\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (;s < n.length; ++s) {\n const t = n[s];\n if (i >= this.Ke.length || !this.He(this.Ke[i++], t)) return !1;\n }\n return !0;\n }\n We(t) {\n for (const e of this.Ge) if (this.ze(e, t)) return !0;\n return !1;\n }\n ze(t, e) {\n if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;\n const n = \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;\n return 2 /* IndexKind.CONTAINS */ === e.kind === n;\n }\n He(t, e) {\n return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && \"asc\" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && \"desc\" /* Direction.DESCENDING */ === t.dir);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */ function Rr(t) {\n var e, n;\n if (M(t instanceof Re || t instanceof be), t instanceof Re) {\n if (t instanceof Be) {\n const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => Re.create(t.field, \"==\" /* Operator.EQUAL */ , e)))) || [];\n return be.create(s, \"or\" /* CompositeOperator.OR */);\n }\n // We have reached other kinds of field filters.\n return t;\n }\n // We have a composite filter.\n const s = t.filters.map((t => Rr(t)));\n return be.create(s, t.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n * <p>Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */ function br(t) {\n if (0 === t.getFilters().length) return [];\n const e = Sr(Rr(t));\n return M(Vr(e)), Pr(e) || vr(e) ? [ e ] : e.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Pr(t) {\n return t instanceof Re;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */ function vr(t) {\n return t instanceof be && Ve(t);\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */ function Vr(t) {\n return Pr(t) || vr(t) || \n /**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\n function(t) {\n if (t instanceof be && ve(t)) {\n for (const e of t.getFilters()) if (!Pr(e) && !vr(e)) return !1;\n return !0;\n }\n return !1;\n }(t);\n}\n\nfunction Sr(t) {\n if (M(t instanceof Re || t instanceof be), t instanceof Re) return t;\n if (1 === t.filters.length) return Sr(t.filters[0]);\n // Compute DNF for each of the subfilters first\n const e = t.filters.map((t => Sr(t)));\n let n = be.create(e, t.op);\n return n = xr(n), Vr(n) ? n : (M(n instanceof be), M(Pe(n)), M(n.filters.length > 1), \n n.filters.reduce(((t, e) => Dr(t, e))));\n}\n\nfunction Dr(t, e) {\n let n;\n return M(t instanceof Re || t instanceof be), M(e instanceof Re || e instanceof be), \n // FieldFilter FieldFilter\n n = t instanceof Re ? e instanceof Re ? function(t, e) {\n // Conjunction distribution for two field filters is the conjunction of them.\n return be.create([ t, e ], \"and\" /* CompositeOperator.AND */);\n }(t, e) : Cr(t, e) : e instanceof Re ? Cr(e, t) : function(t, e) {\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n // Case 1 is a merge.\n if (M(t.filters.length > 0 && e.filters.length > 0), Pe(t) && Pe(e)) return xe(t, e.getFilters());\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const n = ve(t) ? t : e, s = ve(t) ? e : t, i = n.filters.map((t => Dr(t, s)));\n return be.create(i, \"or\" /* CompositeOperator.OR */);\n }(t, e), xr(n);\n}\n\nfunction Cr(t, e) {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (Pe(e)) \n // Case 1\n return xe(e, t.getFilters());\n {\n // Case 2\n const n = e.filters.map((e => Dr(t, e)));\n return be.create(n, \"or\" /* CompositeOperator.OR */);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n * <ul>\n * <li>A | (B | C) == (A | B) | C == (A | B | C)\n * <li>A & (B & C) == (A & B) & C == (A & B & C)\n * </ul>\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */ function xr(t) {\n if (M(t instanceof Re || t instanceof be), t instanceof Re) return t;\n const e = t.getFilters();\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (1 === e.length) return xr(e[0]);\n // Associativity applied to a flat composite filter results is itself.\n if (Se(t)) return t;\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const n = e.map((t => xr(t))), s = [];\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n return n.forEach((e => {\n e instanceof Re ? s.push(e) : e instanceof be && (e.op === t.op ? \n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n s.push(...e.filters) : \n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n s.push(e));\n })), 1 === s.length ? s[0] : be.create(s, t.op);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class Nr {\n constructor() {\n this.Je = new kr;\n }\n addToCollectionParentIndex(t, e) {\n return this.Je.add(e), At.resolve();\n }\n getCollectionParents(t, e) {\n return At.resolve(this.Je.getEntries(e));\n }\n addFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n deleteFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n getDocumentsMatchingTarget(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve(null);\n }\n getIndexType(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve(0 /* IndexType.NONE */);\n }\n getFieldIndexes(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve([]);\n }\n getNextCollectionGroupToUpdate(t) {\n // Field indices are not supported with memory persistence.\n return At.resolve(null);\n }\n getMinOffset(t, e) {\n return At.resolve(yt.min());\n }\n getMinOffsetFromCollectionGroup(t, e) {\n return At.resolve(yt.min());\n }\n updateCollectionGroup(t, e, n) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n updateIndexEntries(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class kr {\n constructor() {\n this.index = {};\n }\n // Returns false if the entry already existed.\n add(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new We(rt.comparator), i = !s.has(n);\n return this.index[e] = s.add(n), i;\n }\n has(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e];\n return s && s.has(n);\n }\n getEntries(t) {\n return (this.index[t] || new We(rt.comparator)).toArray();\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Or = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass Mr {\n constructor(t, e) {\n this.user = t, this.databaseId = e, \n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n this.Ye = new kr, \n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n this.Xe = new ls((t => nn(t)), ((t, e) => sn(t, e))), this.uid = t.uid || \"\";\n }\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */ addToCollectionParentIndex(t, e) {\n if (!this.Ye.has(e)) {\n const n = e.lastSegment(), s = e.popLast();\n t.addOnCommittedListener((() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.Ye.add(e);\n }));\n const i = {\n collectionId: n,\n parent: mi(s)\n };\n return Fr(t).put(i);\n }\n return At.resolve();\n }\n getCollectionParents(t, e) {\n const n = [], s = IDBKeyRange.bound([ e, \"\" ], [ et(e), \"\" ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return Fr(t).W(s).next((t => {\n for (const s of t) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (s.collectionId !== e) break;\n n.push(pi(s.parent));\n }\n return n;\n }));\n }\n addFieldIndex(t, e) {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const n = Br(t), s = function(t) {\n return {\n indexId: t.indexId,\n collectionGroup: t.collectionGroup,\n fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))\n };\n }(e);\n delete s.indexId;\n // `indexId` is auto-populated by IndexedDb\n const i = n.add(s);\n if (e.indexState) {\n const n = Lr(t);\n return i.next((t => {\n n.put(ur(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));\n }));\n }\n return i.next();\n }\n deleteFieldIndex(t, e) {\n const n = Br(t), s = Lr(t), i = $r(t);\n return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0))));\n }\n getDocumentsMatchingTarget(t, e) {\n const n = $r(t);\n let s = !0;\n const i = new Map;\n return At.forEach(this.Ze(e), (e => this.tn(t, e).next((t => {\n s && (s = !!t), i.set(e, t);\n })))).next((() => {\n if (s) {\n let t = Es();\n const s = [];\n return At.forEach(i, ((i, r) => {\n var o;\n C(\"IndexedDbIndexManager\", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(\",\")}`} to execute ${nn(e)}`);\n const u = function(t, e) {\n const n = ht(e);\n if (void 0 === n) return null;\n for (const e of on(t, n.fieldPath)) switch (e.op) {\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return e.value.arrayValue.values || [];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ e.value ];\n // Remaining filters are not array filters.\n }\n return null;\n }\n /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (r, i), c = function(t, e) {\n const n = new Map;\n for (const s of lt(e)) for (const e of on(t, s.fieldPath)) switch (e.op) {\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n n.set(s.fieldPath.canonicalString(), e.value);\n break;\n\n case \"not-in\" /* Operator.NOT_IN */ :\n case \"!=\" /* Operator.NOT_EQUAL */ :\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());\n // Remaining filters cannot be used as notIn bounds.\n }\n return null;\n }\n /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */ (r, i), a = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const i of lt(e)) {\n const e = 0 /* IndexKind.ASCENDING */ === i.kind ? un(t, i.fieldPath, t.startAt) : cn(t, i.fieldPath, t.startAt);\n n.push(e.value), s && (s = e.inclusive);\n }\n return new Ie(n, s);\n }\n /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */ (r, i), h = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const i of lt(e)) {\n const e = 0 /* IndexKind.ASCENDING */ === i.kind ? cn(t, i.fieldPath, t.endAt) : un(t, i.fieldPath, t.endAt);\n n.push(e.value), s && (s = e.inclusive);\n }\n return new Ie(n, s);\n }(r, i), l = this.en(i, r, a), f = this.en(i, r, h), d = this.nn(i, r, c), _ = this.sn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);\n return At.forEach(_, (i => n.J(i, e.limit).next((e => {\n e.forEach((e => {\n const n = ct.fromSegments(e.documentKey);\n t.has(n) || (t = t.add(n), s.push(n));\n }));\n }))));\n })).next((() => s));\n }\n return At.resolve(null);\n }));\n }\n Ze(t) {\n let e = this.Xe.get(t);\n if (e) return e;\n if (0 === t.filters.length) e = [ t ]; else {\n e = br(be.create(t.filters, \"and\" /* CompositeOperator.AND */)).map((e => en(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));\n }\n return this.Xe.set(t, e), e;\n }\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */ sn(t, e, n, s, i, r, o) {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];\n for (let h = 0; h < u; ++h) {\n const u = e ? this.rn(e[h / c]) : Or, l = this.on(t, u, n[h % c], s), f = this.un(t, u, i[h % c], r), d = o.map((e => this.on(t, u, e, \n /* inclusive= */ !0)));\n a.push(...this.createRange(l, f, d));\n }\n return a;\n }\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */ on(t, e, n, s) {\n const i = new Ir(t, ct.empty(), e, n);\n return s ? i : i.Ue();\n }\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */ un(t, e, n, s) {\n const i = new Ir(t, ct.empty(), e, n);\n return s ? i.Ue() : i;\n }\n tn(t, e) {\n const n = new Ar(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();\n return this.getFieldIndexes(t, s).next((t => {\n // Return the index with the most number of segments.\n let e = null;\n for (const s of t) {\n n.je(s) && (!e || s.fields.length > e.fields.length) && (e = s);\n }\n return e;\n }));\n }\n getIndexType(t, e) {\n let n = 2 /* IndexType.FULL */;\n const s = this.Ze(e);\n return At.forEach(s, (e => this.tn(t, e).next((t => {\n t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {\n let e = new We(ut.comparator), n = !1;\n for (const s of t.filters) for (const t of s.getFlattenedFilters()) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n t.field.isKeyField() || (\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));\n for (const n of t.orderBy) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n n.field.isKeyField() || (e = e.add(n.field));\n return e.size + (n ? 1 : 0);\n }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;\n })))).next((() => \n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n function(t) {\n return null !== t.limit;\n }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));\n }\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */ cn(t, e) {\n const n = new pr;\n for (const s of lt(t)) {\n const t = e.data.field(s.fieldPath);\n if (null == t) return null;\n const i = n.qe(s.kind);\n dr.Ie.ue(t, i);\n }\n return n.Fe();\n }\n /** Encodes a single value to the ascending index format. */ rn(t) {\n const e = new pr;\n return dr.Ie.ue(t, e.qe(0 /* IndexKind.ASCENDING */)), e.Fe();\n }\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */ an(t, e) {\n const n = new pr;\n return dr.Ie.ue(ce(this.databaseId, e), n.qe(function(t) {\n const e = lt(t);\n return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;\n }(t))), n.Fe();\n }\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */ nn(t, e, n) {\n if (null === n) return [];\n let s = [];\n s.push(new pr);\n let i = 0;\n for (const r of lt(t)) {\n const t = n[i++];\n for (const n of s) if (this.hn(e, r.fieldPath) && he(t)) s = this.ln(s, r, t); else {\n const e = n.qe(r.kind);\n dr.Ie.ue(t, e);\n }\n }\n return this.fn(s);\n }\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */ en(t, e, n) {\n return this.nn(t, e, n.position);\n }\n /** Returns the byte representation for the provided encoders. */ fn(t) {\n const e = [];\n for (let n = 0; n < t.length; ++n) e[n] = t[n].Fe();\n return e;\n }\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */ ln(t, e, n) {\n const s = [ ...t ], i = [];\n for (const t of n.arrayValue.values || []) for (const n of s) {\n const s = new pr;\n s.seed(n.Fe()), dr.Ie.ue(t, s.qe(e.kind)), i.push(s);\n }\n return i;\n }\n hn(t, e) {\n return !!t.filters.find((t => t instanceof Re && t.field.isEqual(e) && (\"in\" /* Operator.IN */ === t.op || \"not-in\" /* Operator.NOT_IN */ === t.op)));\n }\n getFieldIndexes(t, e) {\n const n = Br(t), s = Lr(t);\n return (e ? n.W(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)) : n.W()).next((t => {\n const e = [];\n return At.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {\n e.push(function(t, e) {\n const n = e ? new wt(e.sequenceNumber, new yt(tr(e.readTime), new ct(pi(e.documentKey)), e.largestBatchId)) : wt.empty(), s = t.fields.map((([t, e]) => new dt(ut.fromServerFormat(t), e)));\n return new at(t.indexId, t.collectionGroup, s, n);\n }(t, n));\n })))).next((() => e));\n }));\n }\n getNextCollectionGroupToUpdate(t) {\n return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {\n const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;\n return 0 !== n ? n : Z(t.collectionGroup, e.collectionGroup);\n })), t[0].collectionGroup)));\n }\n updateCollectionGroup(t, e, n) {\n const s = Br(t), i = Lr(t);\n return this.dn(t).next((t => s.W(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)).next((e => At.forEach(e, (e => i.put(ur(e.indexId, this.user, t, n))))))));\n }\n updateIndexEntries(t, e) {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const n = new Map;\n return At.forEach(e, ((e, s) => {\n const i = n.get(e.collectionGroup);\n return (i ? At.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i), \n At.forEach(i, (n => this._n(t, e, n).next((e => {\n const i = this.wn(s, n);\n return e.isEqual(i) ? At.resolve() : this.mn(t, s, n, e, i);\n })))))));\n }));\n }\n gn(t, e, n, s) {\n return $r(t).put({\n indexId: s.indexId,\n uid: this.uid,\n arrayValue: s.arrayValue,\n directionalValue: s.directionalValue,\n orderedDocumentKey: this.an(n, e.key),\n documentKey: e.key.path.toArray()\n });\n }\n yn(t, e, n, s) {\n return $r(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.an(n, e.key), e.key.path.toArray() ]);\n }\n _n(t, e, n) {\n const s = $r(t);\n let i = new We(Tr);\n return s.Z({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only([ n.indexId, this.uid, this.an(n, e) ])\n }, ((t, s) => {\n i = i.add(new Ir(n.indexId, e, s.arrayValue, s.directionalValue));\n })).next((() => i));\n }\n /** Creates the index entries for the given document. */ wn(t, e) {\n let n = new We(Tr);\n const s = this.cn(e, t);\n if (null == s) return n;\n const i = ht(e);\n if (null != i) {\n const r = t.data.field(i.fieldPath);\n if (he(r)) for (const i of r.arrayValue.values || []) n = n.add(new Ir(e.indexId, t.key, this.rn(i), s));\n } else n = n.add(new Ir(e.indexId, t.key, Or, s));\n return n;\n }\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */ mn(t, e, n, s, i) {\n C(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", e.key);\n const r = [];\n return function(t, e, n, s, i) {\n const r = t.getIterator(), o = e.getIterator();\n let u = He(r), c = He(o);\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n for (;u || c; ) {\n let t = !1, e = !1;\n if (u && c) {\n const s = n(u, c);\n s < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n e = !0 : s > 0 && (\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n t = !0);\n } else null != u ? e = !0 : t = !0;\n t ? (s(c), c = He(o)) : e ? (i(u), u = He(r)) : (u = He(r), c = He(o));\n }\n }(s, i, Tr, (\n /* onAdd= */ s => {\n r.push(this.gn(t, e, n, s));\n }), (\n /* onRemove= */ s => {\n r.push(this.yn(t, e, n, s));\n })), At.waitFor(r);\n }\n dn(t) {\n let e = 1;\n return Lr(t).Z({\n index: \"sequenceNumberIndex\",\n reverse: !0,\n range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n }, ((t, n, s) => {\n s.done(), e = n.sequenceNumber + 1;\n })).next((() => e));\n }\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */ createRange(t, e, n) {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n n = n.sort(((t, e) => Tr(t, e))).filter(((t, e, n) => !e || 0 !== Tr(t, n[e - 1])));\n const s = [];\n s.push(t);\n for (const i of n) {\n const n = Tr(i, t), r = Tr(i, e);\n if (0 === n) \n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n s[0] = t.Ue(); else if (n > 0 && r < 0) \n // `notInValue` is in the middle of the range\n s.push(i), s.push(i.Ue()); else if (r > 0) \n // `notInValue` (and all following values) are out of the range\n break;\n }\n s.push(e);\n const i = [];\n for (let t = 0; t < s.length; t += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.pn(s[t], s[t + 1])) return [];\n const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Or, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Or, [] ];\n i.push(IDBKeyRange.bound(e, n));\n }\n return i;\n }\n pn(t, e) {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return Tr(t, e) > 0;\n }\n getMinOffsetFromCollectionGroup(t, e) {\n return this.getFieldIndexes(t, e).next(qr);\n }\n getMinOffset(t, e) {\n return At.mapArray(this.Ze(e), (e => this.tn(t, e).next((t => t || O())))).next(qr);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function Fr(t) {\n return Gi(t, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function $r(t) {\n return Gi(t, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function Br(t) {\n return Gi(t, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function Lr(t) {\n return Gi(t, \"indexState\");\n}\n\nfunction qr(t) {\n M(0 !== t.length);\n let e = t[0].indexState.offset, n = e.largestBatchId;\n for (let s = 1; s < t.length; s++) {\n const i = t[s].indexState.offset;\n pt(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);\n }\n return new yt(e.readTime, e.documentKey, n);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ur = {\n didRun: !1,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nclass Kr {\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n t, \n // The percentage of sequence numbers that we will attempt to collect\n e, \n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n n) {\n this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;\n }\n static withCacheSize(t) {\n return new Kr(t, Kr.DEFAULT_COLLECTION_PERCENTILE, Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction Gr(t, e, n) {\n const s = t.store(\"mutations\"), i = t.store(\"documentMutations\"), r = [], o = IDBKeyRange.only(n.batchId);\n let u = 0;\n const c = s.Z({\n range: o\n }, ((t, e, n) => (u++, n.delete())));\n r.push(c.next((() => {\n M(1 === u);\n })));\n const a = [];\n for (const t of n.mutations) {\n const s = Ei(e, t.key.path, n.batchId);\n r.push(i.delete(s)), a.push(t.key);\n }\n return At.waitFor(r).next((() => a));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function Qr(t) {\n if (!t) return 0;\n let e;\n if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {\n if (!t.noDocument) throw O();\n e = t.noDocument;\n }\n return JSON.stringify(e).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ Kr.DEFAULT_COLLECTION_PERCENTILE = 10, \nKr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, Kr.DEFAULT = new Kr(41943040, Kr.DEFAULT_COLLECTION_PERCENTILE, Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nKr.DISABLED = new Kr(-1, 0, 0);\n\nclass jr {\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n t, e, n, s) {\n this.userId = t, this.yt = e, this.indexManager = n, this.referenceDelegate = s, \n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n this.In = {};\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */ static re(t, e, n, s) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n M(\"\" !== t.uid);\n const i = t.isAuthenticated() ? t.uid : \"\";\n return new jr(i, e, n, s);\n }\n checkEmpty(t) {\n let e = !0;\n const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return zr(t).Z({\n index: \"userMutationsIndex\",\n range: n\n }, ((t, n, s) => {\n e = !1, s.done();\n })).next((() => e));\n }\n addMutationBatch(t, e, n, s) {\n const i = Hr(t), r = zr(t);\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return r.add({}).next((o => {\n M(\"number\" == typeof o);\n const u = new Qi(o, e, n, s), c = function(t, e, n) {\n const s = n.baseMutations.map((e => ti(t.ie, e))), i = n.mutations.map((e => ti(t.ie, e)));\n return {\n userId: e,\n batchId: n.batchId,\n localWriteTimeMs: n.localWriteTime.toMillis(),\n baseMutations: s,\n mutations: i\n };\n }(this.yt, this.userId, u), a = [];\n let h = new We(((t, e) => Z(t.canonicalString(), e.canonicalString())));\n for (const t of s) {\n const e = Ei(this.userId, t.key.path, o);\n h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Ai));\n }\n return h.forEach((e => {\n a.push(this.indexManager.addToCollectionParentIndex(t, e));\n })), t.addOnCommittedListener((() => {\n this.In[o] = u.keys();\n })), At.waitFor(a).next((() => u));\n }));\n }\n lookupMutationBatch(t, e) {\n return zr(t).get(e).next((t => t ? (M(t.userId === this.userId), er(this.yt, t)) : null));\n }\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n Tn(t, e) {\n return this.In[e] ? At.resolve(this.In[e]) : this.lookupMutationBatch(t, e).next((t => {\n if (t) {\n const n = t.keys();\n return this.In[e] = n, n;\n }\n return null;\n }));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);\n let i = null;\n return zr(t).Z({\n index: \"userMutationsIndex\",\n range: s\n }, ((t, e, s) => {\n e.userId === this.userId && (M(e.batchId >= n), i = er(this.yt, e)), s.done();\n })).next((() => i));\n }\n getHighestUnacknowledgedBatchId(t) {\n const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n let n = -1;\n return zr(t).Z({\n index: \"userMutationsIndex\",\n range: e,\n reverse: !0\n }, ((t, e, s) => {\n n = e.batchId, s.done();\n })).next((() => n));\n }\n getAllMutationBatches(t) {\n const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return zr(t).W(\"userMutationsIndex\", e).next((t => t.map((t => er(this.yt, t)))));\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const n = Ti(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];\n return Hr(t).Z({\n range: s\n }, ((n, s, r) => {\n const [o, u, c] = n, a = pi(u);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n if (o === this.userId && e.path.isEqual(a)) \n // Look up the mutation batch in the store.\n return zr(t).get(c).next((t => {\n if (!t) throw O();\n M(t.userId === this.userId), i.push(er(this.yt, t));\n }));\n r.done();\n })).next((() => i));\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new We(Z);\n const s = [];\n return e.forEach((e => {\n const i = Ti(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = Hr(t).Z({\n range: r\n }, ((t, s, i) => {\n const [r, o, u] = t, c = pi(o);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();\n }));\n s.push(o);\n })), At.waitFor(s).next((() => this.En(t, n)));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n const n = e.path, s = n.length + 1, i = Ti(this.userId, n), r = IDBKeyRange.lowerBound(i);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let o = new We(Z);\n return Hr(t).Z({\n range: r\n }, ((t, e, i) => {\n const [r, u, c] = t, a = pi(u);\n r === this.userId && n.isPrefixOf(a) ? \n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n a.length === s && (o = o.add(c)) : i.done();\n })).next((() => this.En(t, o)));\n }\n En(t, e) {\n const n = [], s = [];\n // TODO(rockwood): Implement this using iterate.\n return e.forEach((e => {\n s.push(zr(t).get(e).next((t => {\n if (null === t) throw O();\n M(t.userId === this.userId), n.push(er(this.yt, t));\n })));\n })), At.waitFor(s).next((() => n));\n }\n removeMutationBatch(t, e) {\n return Gr(t.se, this.userId, e).next((n => (t.addOnCommittedListener((() => {\n this.An(e.batchId);\n })), At.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));\n }\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n An(t) {\n delete this.In[t];\n }\n performConsistencyCheck(t) {\n return this.checkEmpty(t).next((e => {\n if (!e) return At.resolve();\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const n = IDBKeyRange.lowerBound([ this.userId ]);\n const s = [];\n return Hr(t).Z({\n range: n\n }, ((t, e, n) => {\n if (t[0] === this.userId) {\n const e = pi(t[1]);\n s.push(e);\n } else n.done();\n })).next((() => {\n M(0 === s.length);\n }));\n }));\n }\n containsKey(t, e) {\n return Wr(t, this.userId, e);\n }\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n Rn(t) {\n return Jr(t).get(this.userId).next((t => t || {\n userId: this.userId,\n lastAcknowledgedBatchId: -1,\n lastStreamToken: \"\"\n }));\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */ function Wr(t, e, n) {\n const s = Ti(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);\n let o = !1;\n return Hr(t).Z({\n range: r,\n X: !0\n }, ((t, n, s) => {\n const [r, u, /*batchID*/ c] = t;\n r === e && u === i && (o = !0), s.done();\n })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction zr(t) {\n return Gi(t, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function Hr(t) {\n return Gi(t, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function Jr(t) {\n return Gi(t, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass Yr {\n constructor(t) {\n this.bn = t;\n }\n next() {\n return this.bn += 2, this.bn;\n }\n static Pn() {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new Yr(0);\n }\n static vn() {\n // Sync engine assigns target IDs for limbo document detection.\n return new Yr(-1);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Xr {\n constructor(t, e) {\n this.referenceDelegate = t, this.yt = e;\n }\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n allocateTargetId(t) {\n return this.Vn(t).next((e => {\n const n = new Yr(e.highestTargetId);\n return e.highestTargetId = n.next(), this.Sn(t, e).next((() => e.highestTargetId));\n }));\n }\n getLastRemoteSnapshotVersion(t) {\n return this.Vn(t).next((t => st.fromTimestamp(new nt(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));\n }\n getHighestSequenceNumber(t) {\n return this.Vn(t).next((t => t.highestListenSequenceNumber));\n }\n setTargetsMetadata(t, e, n) {\n return this.Vn(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()), \n e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.Sn(t, s))));\n }\n addTargetData(t, e) {\n return this.Dn(t, e).next((() => this.Vn(t).next((n => (n.targetCount += 1, this.Cn(e, n), \n this.Sn(t, n))))));\n }\n updateTargetData(t, e) {\n return this.Dn(t, e);\n }\n removeTargetData(t, e) {\n return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => Zr(t).delete(e.targetId))).next((() => this.Vn(t))).next((e => (M(e.targetCount > 0), \n e.targetCount -= 1, this.Sn(t, e))));\n }\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */ removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return Zr(t).Z(((r, o) => {\n const u = nr(o);\n u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));\n })).next((() => At.waitFor(i))).next((() => s));\n }\n /**\n * Call provided function with each `TargetData` that we have cached.\n */ forEachTarget(t, e) {\n return Zr(t).Z(((t, n) => {\n const s = nr(n);\n e(s);\n }));\n }\n Vn(t) {\n return to(t).get(\"targetGlobalKey\").next((t => (M(null !== t), t)));\n }\n Sn(t, e) {\n return to(t).put(\"targetGlobalKey\", e);\n }\n Dn(t, e) {\n return Zr(t).put(sr(this.yt, e));\n }\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */ Cn(t, e) {\n let n = !1;\n return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0), \n t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, \n n = !0), n;\n }\n getTargetCount(t) {\n return this.Vn(t).next((t => t.targetCount));\n }\n getTargetData(t, e) {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const n = nn(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n let i = null;\n return Zr(t).Z({\n range: s,\n index: \"queryTargetsIndex\"\n }, ((t, n, s) => {\n const r = nr(n);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n sn(e, r.target) && (i = r, s.done());\n })).next((() => i));\n }\n addMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = [], i = eo(t);\n return e.forEach((e => {\n const r = mi(e.path);\n s.push(i.put({\n targetId: n,\n path: r\n })), s.push(this.referenceDelegate.addReference(t, n, e));\n })), At.waitFor(s);\n }\n removeMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = eo(t);\n return At.forEach(e, (e => {\n const i = mi(e.path);\n return At.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);\n }));\n }\n removeMatchingKeysForTargetId(t, e) {\n const n = eo(t), s = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return n.delete(s);\n }\n getMatchingKeysForTargetId(t, e) {\n const n = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0), s = eo(t);\n let i = Es();\n return s.Z({\n range: n,\n X: !0\n }, ((t, e, n) => {\n const s = pi(t[1]), r = new ct(s);\n i = i.add(r);\n })).next((() => i));\n }\n containsKey(t, e) {\n const n = mi(e.path), s = IDBKeyRange.bound([ n ], [ et(n) ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n let i = 0;\n return eo(t).Z({\n index: \"documentTargetsIndex\",\n X: !0,\n range: s\n }, (([t, e], n, s) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n 0 !== t && (i++, s.done());\n })).next((() => i > 0));\n }\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n ne(t, e) {\n return Zr(t).get(e).next((t => t ? nr(t) : null));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function Zr(t) {\n return Gi(t, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function to(t) {\n return Gi(t, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function eo(t) {\n return Gi(t, \"targetDocuments\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function no([t, e], [n, s]) {\n const i = Z(t, n);\n return 0 === i ? Z(e, s) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class so {\n constructor(t) {\n this.xn = t, this.buffer = new We(no), this.Nn = 0;\n }\n kn() {\n return ++this.Nn;\n }\n On(t) {\n const e = [ t, this.kn() ];\n if (this.buffer.size < this.xn) this.buffer = this.buffer.add(e); else {\n const t = this.buffer.last();\n no(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));\n }\n }\n get maxValue() {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()[0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class io {\n constructor(t, e, n) {\n this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Mn = null;\n }\n start() {\n -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Fn(6e4);\n }\n stop() {\n this.Mn && (this.Mn.cancel(), this.Mn = null);\n }\n get started() {\n return null !== this.Mn;\n }\n Fn(t) {\n C(\"LruGarbageCollector\", `Garbage collection scheduled in ${t}ms`), this.Mn = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* TimerId.LruGarbageCollection */ , t, (async () => {\n this.Mn = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (t) {\n Vt(t) ? C(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", t) : await Et(t);\n }\n await this.Fn(3e5);\n }));\n }\n}\n\n/** Implements the steps for LRU garbage collection. */ class ro {\n constructor(t, e) {\n this.$n = t, this.params = e;\n }\n calculateTargetCount(t, e) {\n return this.$n.Bn(t).next((t => Math.floor(e / 100 * t)));\n }\n nthSequenceNumber(t, e) {\n if (0 === e) return At.resolve(Ot.at);\n const n = new so(e);\n return this.$n.forEachTarget(t, (t => n.On(t.sequenceNumber))).next((() => this.$n.Ln(t, (t => n.On(t))))).next((() => n.maxValue));\n }\n removeTargets(t, e, n) {\n return this.$n.removeTargets(t, e, n);\n }\n removeOrphanedDocuments(t, e) {\n return this.$n.removeOrphanedDocuments(t, e);\n }\n collect(t, e) {\n return -1 === this.params.cacheSizeCollectionThreshold ? (C(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n At.resolve(Ur)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (C(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n Ur) : this.qn(t, e)));\n }\n getCacheSize(t) {\n return this.$n.getCacheSize(t);\n }\n qn(t, e) {\n let n, s, i, r, o, c, a;\n const h = Date.now();\n return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (\n // Cap at the configured max\n e > this.params.maximumSequenceNumbersToCollect ? (C(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`), \n s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s, \n o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(), \n this.removeOrphanedDocuments(t, n)))).next((t => {\n if (a = Date.now(), S() <= u.DEBUG) {\n C(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${r - h}ms\\n\\tDetermined least recently used ${s} in ` + (o - r) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (c - o) + \"ms\\n\" + `\\tRemoved ${t} documents in ` + (a - c) + \"ms\\n\" + `Total Duration: ${a - h}ms`);\n }\n return At.resolve({\n didRun: !0,\n sequenceNumbersCollected: s,\n targetsRemoved: i,\n documentsRemoved: t\n });\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Provides LRU functionality for IndexedDB persistence. */\nclass oo {\n constructor(t, e) {\n this.db = t, this.garbageCollector = function(t, e) {\n return new ro(t, e);\n }(this, e);\n }\n Bn(t) {\n const e = this.Un(t);\n return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));\n }\n Un(t) {\n let e = 0;\n return this.Ln(t, (t => {\n e++;\n })).next((() => e));\n }\n forEachTarget(t, e) {\n return this.db.getTargetCache().forEachTarget(t, e);\n }\n Ln(t, e) {\n return this.Kn(t, ((t, n) => e(n)));\n }\n addReference(t, e, n) {\n return uo(t, n);\n }\n removeReference(t, e, n) {\n return uo(t, n);\n }\n removeTargets(t, e, n) {\n return this.db.getTargetCache().removeTargets(t, e, n);\n }\n markPotentiallyOrphaned(t, e) {\n return uo(t, e);\n }\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */ Gn(t, e) {\n return function(t, e) {\n let n = !1;\n return Jr(t).tt((s => Wr(t, s, e).next((t => (t && (n = !0), At.resolve(!t)))))).next((() => n));\n }(t, e);\n }\n removeOrphanedDocuments(t, e) {\n const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];\n let i = 0;\n return this.Kn(t, ((r, o) => {\n if (o <= e) {\n const e = this.Gn(t, r).next((e => {\n if (!e) \n // Our size accounting requires us to read all documents before\n // removing them.\n return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, st.min()), eo(t).delete([ 0, mi(r.path) ]))));\n }));\n s.push(e);\n }\n })).next((() => At.waitFor(s))).next((() => n.apply(t))).next((() => i));\n }\n removeTarget(t, e) {\n const n = e.withSequenceNumber(t.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(t, n);\n }\n updateLimboDocument(t, e) {\n return uo(t, e);\n }\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */ Kn(t, e) {\n const n = eo(t);\n let s, i = Ot.at;\n return n.Z({\n index: \"documentTargetsIndex\"\n }, (([t, n], {path: r, sequenceNumber: o}) => {\n 0 === t ? (\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n i !== Ot.at && e(new ct(pi(s)), i), \n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n i = o, s = r) : \n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n i = Ot.at;\n })).next((() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n i !== Ot.at && e(new ct(pi(s)), i);\n }));\n }\n getCacheSize(t) {\n return this.db.getRemoteDocumentCache().getSize(t);\n }\n}\n\nfunction uo(t, e) {\n return eo(t).put(\n /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\n function(t, e) {\n return {\n targetId: 0,\n path: mi(t.path),\n sequenceNumber: e\n };\n }(e, t.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class co {\n constructor() {\n // A mapping of document key to the new cache entry that should be written.\n this.changes = new ls((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;\n }\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ addEntry(t) {\n this.assertNotApplied(), this.changes.set(t.key, t);\n }\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ removeEntry(t, e) {\n this.assertNotApplied(), this.changes.set(t, Ze.newInvalidDocument(t).setReadTime(e));\n }\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */ getEntry(t, e) {\n this.assertNotApplied();\n const n = this.changes.get(e);\n return void 0 !== n ? At.resolve(n) : this.getFromCache(t, e);\n }\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */ getEntries(t, e) {\n return this.getAllFromCache(t, e);\n }\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */ apply(t) {\n return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);\n }\n /** Helper to assert this.changes is not null */ assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class ao {\n constructor(t) {\n this.yt = t;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ addEntry(t, e, n) {\n return _o(t).put(n);\n }\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ removeEntry(t, e, n) {\n return _o(t).delete(\n /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n function(t, e) {\n const n = t.path.toArray();\n return [ \n /* prefix path */ n.slice(0, n.length - 2), \n /* collection id */ n[n.length - 2], Xi(e), \n /* document id */ n[n.length - 1] ];\n }\n /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (e, n));\n }\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */ updateMetadata(t, e) {\n return this.getMetadata(t).next((n => (n.byteSize += e, this.Qn(t, n))));\n }\n getEntry(t, e) {\n let n = Ze.newInvalidDocument(e);\n return _o(t).Z({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(wo(e))\n }, ((t, s) => {\n n = this.jn(e, s);\n })).next((() => n));\n }\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */ Wn(t, e) {\n let n = {\n size: 0,\n document: Ze.newInvalidDocument(e)\n };\n return _o(t).Z({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(wo(e))\n }, ((t, s) => {\n n = {\n document: this.jn(e, s),\n size: Qr(s)\n };\n })).next((() => n));\n }\n getEntries(t, e) {\n let n = ds();\n return this.zn(t, e, ((t, e) => {\n const s = this.jn(t, e);\n n = n.insert(t, s);\n })).next((() => n));\n }\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */ Hn(t, e) {\n let n = ds(), s = new Ge(ct.comparator);\n return this.zn(t, e, ((t, e) => {\n const i = this.jn(t, e);\n n = n.insert(t, i), s = s.insert(t, Qr(e));\n })).next((() => ({\n documents: n,\n Jn: s\n })));\n }\n zn(t, e, n) {\n if (e.isEmpty()) return At.resolve();\n let s = new We(go);\n e.forEach((t => s = s.add(t)));\n const i = IDBKeyRange.bound(wo(s.first()), wo(s.last())), r = s.getIterator();\n let o = r.getNext();\n return _o(t).Z({\n index: \"documentKeyIndex\",\n range: i\n }, ((t, e, s) => {\n const i = ct.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);\n // Go through keys not found in cache.\n for (;o && go(o, i) < 0; ) n(o, null), o = r.getNext();\n o && o.isEqual(i) && (\n // Key found in cache.\n n(o, e), o = r.hasNext() ? r.getNext() : null), \n // Skip to the next key (if there is one).\n o ? s.j(wo(o)) : s.done();\n })).next((() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;\n }));\n }\n getAllFromCollection(t, e, n) {\n const s = [ e.popLast().toArray(), e.lastSegment(), Xi(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], i = [ e.popLast().toArray(), e.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n return _o(t).W(IDBKeyRange.bound(s, i, !0)).next((t => {\n let e = ds();\n for (const n of t) {\n const t = this.jn(ct.fromSegments(n.prefixPath.concat(n.collectionGroup, n.documentId)), n);\n e = e.insert(t.key, t);\n }\n return e;\n }));\n }\n getAllFromCollectionGroup(t, e, n, s) {\n let i = ds();\n const r = mo(e, n), o = mo(e, yt.max());\n return _o(t).Z({\n index: \"collectionGroupIndex\",\n range: IDBKeyRange.bound(r, o, !0)\n }, ((t, e, n) => {\n const r = this.jn(ct.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);\n i = i.insert(r.key, r), i.size === s && n.done();\n })).next((() => i));\n }\n newChangeBuffer(t) {\n return new lo(this, !!t && t.trackRemovals);\n }\n getSize(t) {\n return this.getMetadata(t).next((t => t.byteSize));\n }\n getMetadata(t) {\n return fo(t).get(\"remoteDocumentGlobalKey\").next((t => (M(!!t), t)));\n }\n Qn(t, e) {\n return fo(t).put(\"remoteDocumentGlobalKey\", e);\n }\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */ jn(t, e) {\n if (e) {\n const t = Ji(this.yt, e);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n if (!(t.isNoDocument() && t.version.isEqual(st.min()))) return t;\n }\n return Ze.newInvalidDocument(t);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */ function ho(t) {\n return new ao(t);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */ class lo extends co {\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(t, e) {\n super(), this.Yn = t, this.trackRemovals = e, \n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n this.Xn = new ls((t => t.toString()), ((t, e) => t.isEqual(e)));\n }\n applyChanges(t) {\n const e = [];\n let n = 0, s = new We(((t, e) => Z(t.canonicalString(), e.canonicalString())));\n return this.changes.forEach(((i, r) => {\n const o = this.Xn.get(i);\n if (e.push(this.Yn.removeEntry(t, i, o.readTime)), r.isValidDocument()) {\n const u = Yi(this.Yn.yt, r);\n s = s.add(i.path.popLast());\n const c = Qr(u);\n n += c - o.size, e.push(this.Yn.addEntry(t, i, u));\n } else if (n -= o.size, this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const n = Yi(this.Yn.yt, r.convertToNoDocument(st.min()));\n e.push(this.Yn.addEntry(t, i, n));\n }\n })), s.forEach((n => {\n e.push(this.Yn.indexManager.addToCollectionParentIndex(t, n));\n })), e.push(this.Yn.updateMetadata(t, n)), At.waitFor(e);\n }\n getFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.Yn.Wn(t, e).next((t => (this.Xn.set(e, {\n size: t.size,\n readTime: t.document.readTime\n }), t.document)));\n }\n getAllFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.Yn.Hn(t, e).next((({documents: t, Jn: e}) => (\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n e.forEach(((e, n) => {\n this.Xn.set(e, {\n size: n,\n readTime: t.get(e).readTime\n });\n })), t)));\n }\n}\n\nfunction fo(t) {\n return Gi(t, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function _o(t) {\n return Gi(t, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function wo(t) {\n const e = t.path.toArray();\n return [ \n /* prefix path */ e.slice(0, e.length - 2), \n /* collection id */ e[e.length - 2], \n /* document id */ e[e.length - 1] ];\n}\n\nfunction mo(t, e) {\n const n = e.documentKey.path.toArray();\n return [ \n /* collection id */ t, Xi(e.readTime), \n /* prefix path */ n.slice(0, n.length - 2), \n /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function go(t, e) {\n const n = t.path.toArray(), s = e.path.toArray();\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let i = 0;\n for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = Z(n[t], s[t]), \n i) return i;\n return i = Z(n.length, s.length), i || (i = Z(n[n.length - 2], s[s.length - 2]), \n i || Z(n[n.length - 1], s[s.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nclass yo {\n constructor(t, \n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n e) {\n this.overlayedDocument = t, this.mutatedFields = e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */ class po {\n constructor(t, e, n, s) {\n this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n, \n this.indexManager = s;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */ getDocument(t, e) {\n let n = null;\n return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Jn(n.mutation, t, Je.empty(), nt.now()), \n t)));\n }\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */ getDocuments(t, e) {\n return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, Es()).next((() => e))));\n }\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */ getLocalViewOfDocuments(t, e, n = Es()) {\n const s = gs();\n return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {\n let e = ws();\n return t.forEach(((t, n) => {\n e = e.insert(t, n.overlayedDocument);\n })), e;\n }))));\n }\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */ getOverlayedDocuments(t, e) {\n const n = gs();\n return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, Es())));\n }\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */ populateOverlays(t, e, n) {\n const s = [];\n return n.forEach((t => {\n e.has(t) || s.push(t);\n })), this.documentOverlayCache.getOverlays(t, s).next((t => {\n t.forEach(((t, n) => {\n e.set(t, n);\n }));\n }));\n }\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */ computeViews(t, e, n, s) {\n let i = ds();\n const r = ps(), o = ps();\n return e.forEach(((t, e) => {\n const o = n.get(e.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n s.has(e.key) && (void 0 === o || o.mutation instanceof ts) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()), \n Jn(o.mutation, e, o.mutation.getFieldMask(), nt.now())) : \n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n r.set(e.key, Je.empty());\n })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))), \n e.forEach(((t, e) => {\n var n;\n return o.set(t, new yo(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));\n })), o)));\n }\n recalculateAndSaveOverlays(t, e) {\n const n = ps();\n // A reverse lookup map from batch id to the documents within that batch.\n let s = new Ge(((t, e) => t - e)), i = Es();\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {\n for (const i of t) i.keys().forEach((t => {\n const r = e.get(t);\n if (null === r) return;\n let o = n.get(t) || Je.empty();\n o = i.applyToLocalView(r, o), n.set(t, o);\n const u = (s.get(i.batchId) || Es()).add(t);\n s = s.insert(i.batchId, u);\n }));\n })).next((() => {\n const r = [], o = s.getReverseIterator();\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n for (;o.hasNext(); ) {\n const s = o.getNext(), u = s.key, c = s.value, a = ys();\n c.forEach((t => {\n if (!i.has(t)) {\n const s = zn(e.get(t), n.get(t));\n null !== s && a.set(t, s), i = i.add(t);\n }\n })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));\n }\n return At.waitFor(r);\n })).next((() => n));\n }\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {\n return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));\n }\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n */ getDocumentsMatchingQuery(t, e, n) {\n /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n return function(t) {\n return ct.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);\n }\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n * <p>The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */ getNextDocuments(t, e, n, s) {\n return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {\n const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : At.resolve(gs());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let o = -1, u = i;\n return r.next((e => At.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId), \n i.get(e) ? At.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {\n u = u.insert(e, t);\n }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, Es()))).next((t => ({\n batchId: o,\n changes: ms(t)\n })))));\n }));\n }\n getDocumentsMatchingDocumentQuery(t, e) {\n // Just do a simple document lookup.\n return this.getDocument(t, new ct(e)).next((t => {\n let e = ws();\n return t.isFoundDocument() && (e = e.insert(t.key, t)), e;\n }));\n }\n getDocumentsMatchingCollectionGroupQuery(t, e, n) {\n const s = e.collectionGroup;\n let i = ws();\n return this.indexManager.getCollectionParents(t, s).next((r => At.forEach(r, (r => {\n const o = function(t, e) {\n return new an(e, \n /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(e, r.child(s));\n return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {\n t.forEach(((t, e) => {\n i = i.insert(t, e);\n }));\n }));\n })).next((() => i))));\n }\n getDocumentsMatchingCollectionQuery(t, e, n) {\n // Query the remote documents and overlay mutations.\n let s;\n return this.remoteDocumentCache.getAllFromCollection(t, e.path, n).next((i => (s = i, \n this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId)))).next((t => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n t.forEach(((t, e) => {\n const n = e.getKey();\n null === s.get(n) && (s = s.insert(n, Ze.newInvalidDocument(n)));\n }));\n // Apply the overlays and match against the query.\n let n = ws();\n return s.forEach(((s, i) => {\n const r = t.get(s);\n void 0 !== r && Jn(r.mutation, i, Je.empty(), nt.now()), \n // Finally, insert the documents that still match the query\n An(e, i) && (n = n.insert(s, i));\n })), n;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Io {\n constructor(t) {\n this.yt = t, this.Zn = new Map, this.ts = new Map;\n }\n getBundleMetadata(t, e) {\n return At.resolve(this.Zn.get(e));\n }\n saveBundleMetadata(t, e) {\n /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n var n;\n return this.Zn.set(e.id, {\n id: (n = e).id,\n version: n.version,\n createTime: qs(n.createTime)\n }), At.resolve();\n }\n getNamedQuery(t, e) {\n return At.resolve(this.ts.get(e));\n }\n saveNamedQuery(t, e) {\n return this.ts.set(e.name, function(t) {\n return {\n name: t.name,\n query: ir(t.bundledQuery),\n readTime: qs(t.readTime)\n };\n }(e)), At.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class To {\n constructor() {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n this.overlays = new Ge(ct.comparator), this.es = new Map;\n }\n getOverlay(t, e) {\n return At.resolve(this.overlays.get(e));\n }\n getOverlays(t, e) {\n const n = gs();\n return At.forEach(e, (e => this.getOverlay(t, e).next((t => {\n null !== t && n.set(e, t);\n })))).next((() => n));\n }\n saveOverlays(t, e, n) {\n return n.forEach(((n, s) => {\n this.oe(t, e, s);\n })), At.resolve();\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = this.es.get(n);\n return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))), \n this.es.delete(n)), At.resolve();\n }\n getOverlaysForCollection(t, e, n) {\n const s = gs(), i = e.length + 1, r = new ct(e.child(\"\")), o = this.overlays.getIteratorFrom(r);\n for (;o.hasNext(); ) {\n const t = o.getNext().value, r = t.getKey();\n if (!e.isPrefixOf(r.path)) break;\n // Documents from sub-collections\n r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));\n }\n return At.resolve(s);\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n let i = new Ge(((t, e) => t - e));\n const r = this.overlays.getIterator();\n for (;r.hasNext(); ) {\n const t = r.getNext().value;\n if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {\n let e = i.get(t.largestBatchId);\n null === e && (e = gs(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);\n }\n }\n const o = gs(), u = i.getIterator();\n for (;u.hasNext(); ) {\n if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;\n }\n return At.resolve(o);\n }\n oe(t, e, n) {\n // Remove the association of the overlay to its batch id.\n const s = this.overlays.get(n.key);\n if (null !== s) {\n const t = this.es.get(s.largestBatchId).delete(n.key);\n this.es.set(s.largestBatchId, t);\n }\n this.overlays = this.overlays.insert(n.key, new Wi(e, n));\n // Create the association of this overlay to the given largestBatchId.\n let i = this.es.get(e);\n void 0 === i && (i = Es(), this.es.set(e, i)), this.es.set(e, i.add(n.key));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class Eo {\n constructor() {\n // A set of outstanding references to a document sorted by key.\n this.ns = new We(Ao.ss), \n // A set of outstanding references to a document sorted by target id.\n this.rs = new We(Ao.os);\n }\n /** Returns true if the reference set contains no references. */ isEmpty() {\n return this.ns.isEmpty();\n }\n /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {\n const n = new Ao(t, e);\n this.ns = this.ns.add(n), this.rs = this.rs.add(n);\n }\n /** Add references to the given document keys for the given ID. */ us(t, e) {\n t.forEach((t => this.addReference(t, e)));\n }\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */ removeReference(t, e) {\n this.cs(new Ao(t, e));\n }\n hs(t, e) {\n t.forEach((t => this.removeReference(t, e)));\n }\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */ ls(t) {\n const e = new ct(new rt([])), n = new Ao(e, t), s = new Ao(e, t + 1), i = [];\n return this.rs.forEachInRange([ n, s ], (t => {\n this.cs(t), i.push(t.key);\n })), i;\n }\n fs() {\n this.ns.forEach((t => this.cs(t)));\n }\n cs(t) {\n this.ns = this.ns.delete(t), this.rs = this.rs.delete(t);\n }\n ds(t) {\n const e = new ct(new rt([])), n = new Ao(e, t), s = new Ao(e, t + 1);\n let i = Es();\n return this.rs.forEachInRange([ n, s ], (t => {\n i = i.add(t.key);\n })), i;\n }\n containsKey(t) {\n const e = new Ao(t, 0), n = this.ns.firstAfterOrEqual(e);\n return null !== n && t.isEqual(n.key);\n }\n}\n\nclass Ao {\n constructor(t, e) {\n this.key = t, this._s = e;\n }\n /** Compare by key then by ID */ static ss(t, e) {\n return ct.comparator(t.key, e.key) || Z(t._s, e._s);\n }\n /** Compare by ID then by key */ static os(t, e) {\n return Z(t._s, e._s) || ct.comparator(t.key, e.key);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Ro {\n constructor(t, e) {\n this.indexManager = t, this.referenceDelegate = e, \n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [], \n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.ws = 1, \n /** An ordered mapping between documents and the mutations batch IDs. */\n this.gs = new We(Ao.ss);\n }\n checkEmpty(t) {\n return At.resolve(0 === this.mutationQueue.length);\n }\n addMutationBatch(t, e, n, s) {\n const i = this.ws;\n this.ws++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];\n const r = new Qi(i, e, n, s);\n this.mutationQueue.push(r);\n // Track references by document key and index collection parents.\n for (const e of s) this.gs = this.gs.add(new Ao(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());\n return At.resolve(r);\n }\n lookupMutationBatch(t, e) {\n return At.resolve(this.ys(e));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = this.ps(n), i = s < 0 ? 0 : s;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n return At.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);\n }\n getHighestUnacknowledgedBatchId() {\n return At.resolve(0 === this.mutationQueue.length ? -1 : this.ws - 1);\n }\n getAllMutationBatches(t) {\n return At.resolve(this.mutationQueue.slice());\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n const n = new Ao(e, 0), s = new Ao(e, Number.POSITIVE_INFINITY), i = [];\n return this.gs.forEachInRange([ n, s ], (t => {\n const e = this.ys(t._s);\n i.push(e);\n })), At.resolve(i);\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new We(Z);\n return e.forEach((t => {\n const e = new Ao(t, 0), s = new Ao(t, Number.POSITIVE_INFINITY);\n this.gs.forEachInRange([ e, s ], (t => {\n n = n.add(t._s);\n }));\n })), At.resolve(this.Is(n));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const n = e.path, s = n.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let i = n;\n ct.isDocumentKey(i) || (i = i.child(\"\"));\n const r = new Ao(new ct(i), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let o = new We(Z);\n return this.gs.forEachWhile((t => {\n const e = t.key.path;\n return !!n.isPrefixOf(e) && (\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n e.length === s && (o = o.add(t._s)), !0);\n }), r), At.resolve(this.Is(o));\n }\n Is(t) {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const e = [];\n return t.forEach((t => {\n const n = this.ys(t);\n null !== n && e.push(n);\n })), e;\n }\n removeMutationBatch(t, e) {\n M(0 === this.Ts(e.batchId, \"removed\")), this.mutationQueue.shift();\n let n = this.gs;\n return At.forEach(e.mutations, (s => {\n const i = new Ao(s.key, e.batchId);\n return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);\n })).next((() => {\n this.gs = n;\n }));\n }\n An(t) {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n containsKey(t, e) {\n const n = new Ao(e, 0), s = this.gs.firstAfterOrEqual(n);\n return At.resolve(e.isEqual(s && s.key));\n }\n performConsistencyCheck(t) {\n return this.mutationQueue.length, At.resolve();\n }\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */ Ts(t, e) {\n return this.ps(t);\n }\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */ ps(t) {\n if (0 === this.mutationQueue.length) \n // As an index this is past the end of the queue\n return 0;\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n return t - this.mutationQueue[0].batchId;\n }\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */ ys(t) {\n const e = this.ps(t);\n if (e < 0 || e >= this.mutationQueue.length) return null;\n return this.mutationQueue[e];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass bo {\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(t) {\n this.Es = t, \n /** Underlying cache of documents and their read times. */\n this.docs = new Ge(ct.comparator), \n /** Size of all cached documents. */\n this.size = 0;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ addEntry(t, e) {\n const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Es(e);\n return this.docs = this.docs.insert(n, {\n document: e.mutableCopy(),\n size: r\n }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());\n }\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }\n getEntry(t, e) {\n const n = this.docs.get(e);\n return At.resolve(n ? n.document.mutableCopy() : Ze.newInvalidDocument(e));\n }\n getEntries(t, e) {\n let n = ds();\n return e.forEach((t => {\n const e = this.docs.get(t);\n n = n.insert(t, e ? e.document.mutableCopy() : Ze.newInvalidDocument(t));\n })), At.resolve(n);\n }\n getAllFromCollection(t, e, n) {\n let s = ds();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const i = new ct(e.child(\"\")), r = this.docs.getIteratorFrom(i);\n for (;r.hasNext(); ) {\n const {key: t, value: {document: i}} = r.getNext();\n if (!e.isPrefixOf(t.path)) break;\n t.path.length > e.length + 1 || (pt(gt(i), n) <= 0 || (s = s.insert(i.key, i.mutableCopy())));\n }\n return At.resolve(s);\n }\n getAllFromCollectionGroup(t, e, n, s) {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n O();\n }\n As(t, e) {\n return At.forEach(this.docs, (t => e(t)));\n }\n newChangeBuffer(t) {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new Po(this);\n }\n getSize(t) {\n return At.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass Po extends co {\n constructor(t) {\n super(), this.Yn = t;\n }\n applyChanges(t) {\n const e = [];\n return this.changes.forEach(((n, s) => {\n s.isValidDocument() ? e.push(this.Yn.addEntry(t, s)) : this.Yn.removeEntry(n);\n })), At.waitFor(e);\n }\n getFromCache(t, e) {\n return this.Yn.getEntry(t, e);\n }\n getAllFromCache(t, e) {\n return this.Yn.getEntries(t, e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class vo {\n constructor(t) {\n this.persistence = t, \n /**\n * Maps a target to the data about that target\n */\n this.Rs = new ls((t => nn(t)), sn), \n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = st.min(), \n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0, \n /** The highest sequence number encountered. */\n this.bs = 0, \n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.Ps = new Eo, this.targetCount = 0, this.vs = Yr.Pn();\n }\n forEachTarget(t, e) {\n return this.Rs.forEach(((t, n) => e(n))), At.resolve();\n }\n getLastRemoteSnapshotVersion(t) {\n return At.resolve(this.lastRemoteSnapshotVersion);\n }\n getHighestSequenceNumber(t) {\n return At.resolve(this.bs);\n }\n allocateTargetId(t) {\n return this.highestTargetId = this.vs.next(), At.resolve(this.highestTargetId);\n }\n setTargetsMetadata(t, e, n) {\n return n && (this.lastRemoteSnapshotVersion = n), e > this.bs && (this.bs = e), \n At.resolve();\n }\n Dn(t) {\n this.Rs.set(t.target, t);\n const e = t.targetId;\n e > this.highestTargetId && (this.vs = new Yr(e), this.highestTargetId = e), t.sequenceNumber > this.bs && (this.bs = t.sequenceNumber);\n }\n addTargetData(t, e) {\n return this.Dn(e), this.targetCount += 1, At.resolve();\n }\n updateTargetData(t, e) {\n return this.Dn(e), At.resolve();\n }\n removeTargetData(t, e) {\n return this.Rs.delete(e.target), this.Ps.ls(e.targetId), this.targetCount -= 1, \n At.resolve();\n }\n removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return this.Rs.forEach(((r, o) => {\n o.sequenceNumber <= e && null === n.get(o.targetId) && (this.Rs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)), \n s++);\n })), At.waitFor(i).next((() => s));\n }\n getTargetCount(t) {\n return At.resolve(this.targetCount);\n }\n getTargetData(t, e) {\n const n = this.Rs.get(e) || null;\n return At.resolve(n);\n }\n addMatchingKeys(t, e, n) {\n return this.Ps.us(e, n), At.resolve();\n }\n removeMatchingKeys(t, e, n) {\n this.Ps.hs(e, n);\n const s = this.persistence.referenceDelegate, i = [];\n return s && e.forEach((e => {\n i.push(s.markPotentiallyOrphaned(t, e));\n })), At.waitFor(i);\n }\n removeMatchingKeysForTargetId(t, e) {\n return this.Ps.ls(e), At.resolve();\n }\n getMatchingKeysForTargetId(t, e) {\n const n = this.Ps.ds(e);\n return At.resolve(n);\n }\n containsKey(t, e) {\n return At.resolve(this.Ps.containsKey(e));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass Vo {\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(t, e) {\n this.Vs = {}, this.overlays = {}, this.Ss = new Ot(0), this.Ds = !1, this.Ds = !0, \n this.referenceDelegate = t(this), this.Cs = new vo(this);\n this.indexManager = new Nr, this.remoteDocumentCache = function(t) {\n return new bo(t);\n }((t => this.referenceDelegate.xs(t))), this.yt = new Hi(e), this.Ns = new Io(this.yt);\n }\n start() {\n return Promise.resolve();\n }\n shutdown() {\n // No durable state to ensure is closed on shutdown.\n return this.Ds = !1, Promise.resolve();\n }\n get started() {\n return this.Ds;\n }\n setDatabaseDeletedListener() {\n // No op.\n }\n setNetworkEnabled() {\n // No op.\n }\n getIndexManager(t) {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n getDocumentOverlayCache(t) {\n let e = this.overlays[t.toKey()];\n return e || (e = new To, this.overlays[t.toKey()] = e), e;\n }\n getMutationQueue(t, e) {\n let n = this.Vs[t.toKey()];\n return n || (n = new Ro(e, this.referenceDelegate), this.Vs[t.toKey()] = n), n;\n }\n getTargetCache() {\n return this.Cs;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getBundleCache() {\n return this.Ns;\n }\n runTransaction(t, e, n) {\n C(\"MemoryPersistence\", \"Starting transaction:\", t);\n const s = new So(this.Ss.next());\n return this.referenceDelegate.ks(), n(s).next((t => this.referenceDelegate.Os(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(), \n t)));\n }\n Ms(t, e) {\n return At.or(Object.values(this.Vs).map((n => () => n.containsKey(t, e))));\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class So extends Tt {\n constructor(t) {\n super(), this.currentSequenceNumber = t;\n }\n}\n\nclass Do {\n constructor(t) {\n this.persistence = t, \n /** Tracks all documents that are active in Query views. */\n this.Fs = new Eo, \n /** The list of documents that are potentially GCed after each transaction. */\n this.$s = null;\n }\n static Bs(t) {\n return new Do(t);\n }\n get Ls() {\n if (this.$s) return this.$s;\n throw O();\n }\n addReference(t, e, n) {\n return this.Fs.addReference(n, e), this.Ls.delete(n.toString()), At.resolve();\n }\n removeReference(t, e, n) {\n return this.Fs.removeReference(n, e), this.Ls.add(n.toString()), At.resolve();\n }\n markPotentiallyOrphaned(t, e) {\n return this.Ls.add(e.toString()), At.resolve();\n }\n removeTarget(t, e) {\n this.Fs.ls(e.targetId).forEach((t => this.Ls.add(t.toString())));\n const n = this.persistence.getTargetCache();\n return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n t.forEach((t => this.Ls.add(t.toString())));\n })).next((() => n.removeTargetData(t, e)));\n }\n ks() {\n this.$s = new Set;\n }\n Os(t) {\n // Remove newly orphaned documents.\n const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n return At.forEach(this.Ls, (n => {\n const s = ct.fromPath(n);\n return this.qs(t, s).next((t => {\n t || e.removeEntry(s, st.min());\n }));\n })).next((() => (this.$s = null, e.apply(t))));\n }\n updateLimboDocument(t, e) {\n return this.qs(t, e).next((t => {\n t ? this.Ls.delete(e.toString()) : this.Ls.add(e.toString());\n }));\n }\n xs(t) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n qs(t, e) {\n return At.or([ () => At.resolve(this.Fs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Ms(t, e) ]);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Performs database creation and schema upgrades. */ class Co {\n constructor(t) {\n this.yt = t;\n }\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */ $(t, e, n, s) {\n const i = new Rt(\"createOrUpgrade\", e);\n n < 1 && s >= 1 && (function(t) {\n t.createObjectStore(\"owner\");\n }(t), function(t) {\n t.createObjectStore(\"mutationQueues\", {\n keyPath: \"userId\"\n });\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Ii, {\n unique: !0\n }), t.createObjectStore(\"documentMutations\");\n }\n /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (t), xo(t), function(t) {\n t.createObjectStore(\"remoteDocuments\");\n }(t));\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n let r = At.resolve();\n return n < 3 && s >= 3 && (\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n 0 !== n && (!function(t) {\n t.deleteObjectStore(\"targetDocuments\"), t.deleteObjectStore(\"targets\"), t.deleteObjectStore(\"targetGlobal\");\n }(t), xo(t)), r = r.next((() => \n /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n function(t) {\n const e = t.store(\"targetGlobal\"), n = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: st.min().toTimestamp(),\n targetCount: 0\n };\n return e.put(\"targetGlobalKey\", n);\n }(i)))), n < 4 && s >= 4 && (0 !== n && (\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n r = r.next((() => function(t, e) {\n return e.store(\"mutations\").W().next((n => {\n t.deleteObjectStore(\"mutations\");\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Ii, {\n unique: !0\n });\n const s = e.store(\"mutations\"), i = n.map((t => s.put(t)));\n return At.waitFor(i);\n }));\n }(t, i)))), r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"clientMetadata\", {\n keyPath: \"clientId\"\n });\n }(t);\n }))), n < 5 && s >= 5 && (r = r.next((() => this.Us(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {\n t.createObjectStore(\"remoteDocumentGlobal\");\n }(t), this.Ks(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Gs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.Qs(t, i)))), \n n < 9 && s >= 9 && (r = r.next((() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n !function(t) {\n t.objectStoreNames.contains(\"remoteDocumentChanges\") && t.deleteObjectStore(\"remoteDocumentChanges\");\n }(t);\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n }))), n < 10 && s >= 10 && (r = r.next((() => this.js(i)))), n < 11 && s >= 11 && (r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"bundles\", {\n keyPath: \"bundleId\"\n });\n }(t), function(t) {\n t.createObjectStore(\"namedQueries\", {\n keyPath: \"name\"\n });\n }(t);\n }))), n < 12 && s >= 12 && (r = r.next((() => {\n !function(t) {\n const e = t.createObjectStore(\"documentOverlays\", {\n keyPath: Oi\n });\n e.createIndex(\"collectionPathOverlayIndex\", Mi, {\n unique: !1\n }), e.createIndex(\"collectionGroupOverlayIndex\", Fi, {\n unique: !1\n });\n }(t);\n }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {\n const e = t.createObjectStore(\"remoteDocumentsV14\", {\n keyPath: Ri\n });\n e.createIndex(\"documentKeyIndex\", bi), e.createIndex(\"collectionGroupIndex\", Pi);\n }(t))).next((() => this.Ws(t, i))).next((() => t.deleteObjectStore(\"remoteDocuments\")))), \n n < 14 && s >= 14 && (r = r.next((() => this.zs(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {\n t.createObjectStore(\"indexConfiguration\", {\n keyPath: \"indexId\",\n autoIncrement: !0\n }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n unique: !1\n });\n t.createObjectStore(\"indexState\", {\n keyPath: Ci\n }).createIndex(\"sequenceNumberIndex\", xi, {\n unique: !1\n });\n t.createObjectStore(\"indexEntries\", {\n keyPath: Ni\n }).createIndex(\"documentKeyIndex\", ki, {\n unique: !1\n });\n }(t)))), r;\n }\n Ks(t) {\n let e = 0;\n return t.store(\"remoteDocuments\").Z(((t, n) => {\n e += Qr(n);\n })).next((() => {\n const n = {\n byteSize: e\n };\n return t.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n }));\n }\n Us(t) {\n const e = t.store(\"mutationQueues\"), n = t.store(\"mutations\");\n return e.W().next((e => At.forEach(e, (e => {\n const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);\n return n.W(\"userMutationsIndex\", s).next((n => At.forEach(n, (n => {\n M(n.userId === e.userId);\n const s = er(this.yt, n);\n return Gr(t, e.userId, s).next((() => {}));\n }))));\n }))));\n }\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */ Gs(t) {\n const e = t.store(\"targetDocuments\"), n = t.store(\"remoteDocuments\");\n return t.store(\"targetGlobal\").get(\"targetGlobalKey\").next((t => {\n const s = [];\n return n.Z(((n, i) => {\n const r = new rt(n), o = function(t) {\n return [ 0, mi(t) ];\n }(r);\n s.push(e.get(o).next((n => n ? At.resolve() : (n => e.put({\n targetId: 0,\n path: mi(n),\n sequenceNumber: t.highestListenSequenceNumber\n }))(r))));\n })).next((() => At.waitFor(s)));\n }));\n }\n Qs(t, e) {\n // Create the index.\n t.createObjectStore(\"collectionParents\", {\n keyPath: Di\n });\n const n = e.store(\"collectionParents\"), s = new kr, i = t => {\n if (s.add(t)) {\n const e = t.lastSegment(), s = t.popLast();\n return n.put({\n collectionId: e,\n parent: mi(s)\n });\n }\n };\n // Helper to add an index entry iff we haven't already written it.\n // Index existing remote documents.\n return e.store(\"remoteDocuments\").Z({\n X: !0\n }, ((t, e) => {\n const n = new rt(t);\n return i(n.popLast());\n })).next((() => e.store(\"documentMutations\").Z({\n X: !0\n }, (([t, e, n], s) => {\n const r = pi(e);\n return i(r.popLast());\n }))));\n }\n js(t) {\n const e = t.store(\"targets\");\n return e.Z(((t, n) => {\n const s = nr(n), i = sr(this.yt, s);\n return e.put(i);\n }));\n }\n Ws(t, e) {\n const n = e.store(\"remoteDocuments\"), s = [];\n return n.Z(((t, n) => {\n const i = e.store(\"remoteDocumentsV14\"), r = (o = n, o.document ? new ct(rt.fromString(o.document.name).popFirst(5)) : o.noDocument ? ct.fromSegments(o.noDocument.path) : o.unknownDocument ? ct.fromSegments(o.unknownDocument.path) : O()).path.toArray();\n var o;\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const u = {\n prefixPath: r.slice(0, r.length - 2),\n collectionGroup: r[r.length - 2],\n documentId: r[r.length - 1],\n readTime: n.readTime || [ 0, 0 ],\n unknownDocument: n.unknownDocument,\n noDocument: n.noDocument,\n document: n.document,\n hasCommittedMutations: !!n.hasCommittedMutations\n };\n s.push(i.put(u));\n })).next((() => At.waitFor(s)));\n }\n zs(t, e) {\n const n = e.store(\"mutations\"), s = ho(this.yt), i = new Vo(Do.Bs, this.yt.ie);\n return n.W().next((t => {\n const n = new Map;\n return t.forEach((t => {\n var e;\n let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : Es();\n er(this.yt, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);\n })), At.forEach(n, ((t, n) => {\n const r = new P(n), o = lr.re(this.yt, r), u = i.getIndexManager(r), c = jr.re(r, this.yt, u, i.referenceDelegate);\n return new po(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new Ki(e, Ot.at), t).next();\n }));\n }));\n }\n}\n\nfunction xo(t) {\n t.createObjectStore(\"targetDocuments\", {\n keyPath: Vi\n }).createIndex(\"documentTargetsIndex\", Si, {\n unique: !0\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n t.createObjectStore(\"targets\", {\n keyPath: \"targetId\"\n }).createIndex(\"queryTargetsIndex\", vi, {\n unique: !0\n }), t.createObjectStore(\"targetGlobal\");\n}\n\nconst No = \"Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass ko {\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n t, e, n, s, i, r, o, u, c, \n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n a, h = 15) {\n if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n, \n this.Hs = i, this.window = r, this.document = o, this.Js = c, this.Ys = a, this.Xs = h, \n this.Ss = null, this.Ds = !1, this.isPrimary = !1, this.networkEnabled = !0, \n /** Our window.unload handler, if registered. */\n this.Zs = null, this.inForeground = !1, \n /** Our 'visibilitychange' listener if registered. */\n this.ti = null, \n /** The client metadata refresh task. */\n this.ei = null, \n /** The last time we garbage collected the client metadata object store. */\n this.ni = Number.NEGATIVE_INFINITY, \n /** A listener to notify on primary state changes. */\n this.si = t => Promise.resolve(), !ko.C()) throw new L(B.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n this.referenceDelegate = new oo(this, s), this.ii = e + \"main\", this.yt = new Hi(u), \n this.ri = new bt(this.ii, this.Xs, new Co(this.yt)), this.Cs = new Xr(this.referenceDelegate, this.yt), \n this.remoteDocumentCache = ho(this.yt), this.Ns = new cr, this.window && this.window.localStorage ? this.oi = this.window.localStorage : (this.oi = null, \n !1 === a && x(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n }\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */ start() {\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.ui().then((() => {\n if (!this.isPrimary && !this.allowTabSynchronization) \n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new L(B.FAILED_PRECONDITION, No);\n return this.ci(), this.ai(), this.hi(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (t => this.Cs.getHighestSequenceNumber(t)));\n })).then((t => {\n this.Ss = new Ot(t, this.Js);\n })).then((() => {\n this.Ds = !0;\n })).catch((t => (this.ri && this.ri.close(), Promise.reject(t))));\n }\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ li(t) {\n return this.si = async e => {\n if (this.started) return t(e);\n }, t(this.isPrimary);\n }\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setDatabaseDeletedListener(t) {\n this.ri.L((async e => {\n // Check if an attempt is made to delete IndexedDB.\n null === e.newVersion && await t();\n }));\n }\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setNetworkEnabled(t) {\n this.networkEnabled !== t && (this.networkEnabled = t, \n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.Hs.enqueueAndForget((async () => {\n this.started && await this.ui();\n })));\n }\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */ ui() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (t => Mo(t).put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n }).next((() => {\n if (this.isPrimary) return this.fi(t).next((t => {\n t || (this.isPrimary = !1, this.Hs.enqueueRetryable((() => this.si(!1))));\n }));\n })).next((() => this.di(t))).next((e => this.isPrimary && !e ? this._i(t).next((() => !1)) : !!e && this.wi(t).next((() => !0)))))).catch((t => {\n if (Vt(t)) \n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return C(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", t), this.isPrimary;\n if (!this.allowTabSynchronization) throw t;\n return C(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", t), \n /* isPrimary= */ !1;\n })).then((t => {\n this.isPrimary !== t && this.Hs.enqueueRetryable((() => this.si(t))), this.isPrimary = t;\n }));\n }\n fi(t) {\n return Oo(t).get(\"owner\").next((t => At.resolve(this.mi(t))));\n }\n gi(t) {\n return Mo(t).delete(this.clientId);\n }\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */ async yi() {\n if (this.isPrimary && !this.pi(this.ni, 18e5)) {\n this.ni = Date.now();\n const t = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (t => {\n const e = Gi(t, \"clientMetadata\");\n return e.W().next((t => {\n const n = this.Ii(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));\n // Delete metadata for clients that are no longer considered active.\n return At.forEach(s, (t => e.delete(t.clientId))).next((() => s));\n }));\n })).catch((() => []));\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.oi) for (const e of t) this.oi.removeItem(this.Ti(e.clientId));\n }\n }\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */ hi() {\n this.ei = this.Hs.enqueueAfterDelay(\"client_metadata_refresh\" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.ui().then((() => this.yi())).then((() => this.hi()))));\n }\n /** Checks whether `client` is the local client. */ mi(t) {\n return !!t && t.ownerId === this.clientId;\n }\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */ di(t) {\n if (this.Ys) return At.resolve(!0);\n return Oo(t).get(\"owner\").next((e => {\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (null !== e && this.pi(e.leaseTimestampMs, 5e3) && !this.Ei(e.ownerId)) {\n if (this.mi(e) && this.networkEnabled) return !0;\n if (!this.mi(e)) {\n if (!e.allowTabSynchronization) \n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new L(B.FAILED_PRECONDITION, No);\n return !1;\n }\n }\n return !(!this.networkEnabled || !this.inForeground) || Mo(t).W().next((t => void 0 === this.Ii(t, 5e3).find((t => {\n if (this.clientId !== t.clientId) {\n const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;\n if (e || n && s) return !0;\n }\n return !1;\n }))));\n })).next((t => (this.isPrimary !== t && C(\"IndexedDbPersistence\", `Client ${t ? \"is\" : \"is not\"} eligible for a primary lease.`), \n t)));\n }\n async shutdown() {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this.Ds = !1, this.Ai(), this.ei && (this.ei.cancel(), this.ei = null), this.Ri(), \n this.bi(), \n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.ri.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (t => {\n const e = new Ki(t, Ot.at);\n return this._i(e).next((() => this.gi(e)));\n })), this.ri.close(), \n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.Pi();\n }\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */ Ii(t, e) {\n return t.filter((t => this.pi(t.updateTimeMs, e) && !this.Ei(t.clientId)));\n }\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ vi() {\n return this.runTransaction(\"getActiveClients\", \"readonly\", (t => Mo(t).W().next((t => this.Ii(t, 18e5).map((t => t.clientId))))));\n }\n get started() {\n return this.Ds;\n }\n getMutationQueue(t, e) {\n return jr.re(t, this.yt, e, this.referenceDelegate);\n }\n getTargetCache() {\n return this.Cs;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getIndexManager(t) {\n return new Mr(t, this.yt.ie.databaseId);\n }\n getDocumentOverlayCache(t) {\n return lr.re(this.yt, t);\n }\n getBundleCache() {\n return this.Ns;\n }\n runTransaction(t, e, n) {\n C(\"IndexedDbPersistence\", \"Starting transaction:\", t);\n const s = \"readonly\" === e ? \"readonly\" : \"readwrite\", i = 15 === (r = this.Xs) ? Ui : 14 === r ? qi : 13 === r ? Li : 12 === r ? Bi : 11 === r ? $i : void O();\n /** Returns the object stores for the provided schema. */\n var r;\n let o;\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.ri.runTransaction(t, s, i, (s => (o = new Ki(s, this.Ss ? this.Ss.next() : Ot.at), \n \"readwrite-primary\" === e ? this.fi(o).next((t => !!t || this.di(o))).next((e => {\n if (!e) throw x(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, \n this.Hs.enqueueRetryable((() => this.si(!1))), new L(B.FAILED_PRECONDITION, It);\n return n(o);\n })).next((t => this.wi(o).next((() => t)))) : this.Vi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(), \n t)));\n }\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n Vi(t) {\n return Oo(t).get(\"owner\").next((t => {\n if (null !== t && this.pi(t.leaseTimestampMs, 5e3) && !this.Ei(t.ownerId) && !this.mi(t) && !(this.Ys || this.allowTabSynchronization && t.allowTabSynchronization)) throw new L(B.FAILED_PRECONDITION, No);\n }));\n }\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */ wi(t) {\n const e = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return Oo(t).put(\"owner\", e);\n }\n static C() {\n return bt.C();\n }\n /** Checks the primary lease and removes it if we are the current primary. */ _i(t) {\n const e = Oo(t);\n return e.get(\"owner\").next((t => this.mi(t) ? (C(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n e.delete(\"owner\")) : At.resolve()));\n }\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ pi(t, e) {\n const n = Date.now();\n return !(t < n - e) && (!(t > n) || (x(`Detected an update time that is in the future: ${t} > ${n}`), \n !1));\n }\n ci() {\n null !== this.document && \"function\" == typeof this.document.addEventListener && (this.ti = () => {\n this.Hs.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n this.ui())));\n }, this.document.addEventListener(\"visibilitychange\", this.ti), this.inForeground = \"visible\" === this.document.visibilityState);\n }\n Ri() {\n this.ti && (this.document.removeEventListener(\"visibilitychange\", this.ti), this.ti = null);\n }\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */ ai() {\n var t;\n \"function\" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.Zs = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.Ai(), l() && navigator.appVersion.match(/Version\\/1[45]/) && \n // On Safari 14 and 15, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.Hs.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Hs.enqueueAndForget((() => this.shutdown()));\n }, this.window.addEventListener(\"pagehide\", this.Zs));\n }\n bi() {\n this.Zs && (this.window.removeEventListener(\"pagehide\", this.Zs), this.Zs = null);\n }\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */ Ei(t) {\n var e;\n try {\n const n = null !== (null === (e = this.oi) || void 0 === e ? void 0 : e.getItem(this.Ti(t)));\n return C(\"IndexedDbPersistence\", `Client '${t}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n n;\n } catch (t) {\n // Gracefully handle if LocalStorage isn't working.\n return x(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", t), !1;\n }\n }\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */ Ai() {\n if (this.oi) try {\n this.oi.setItem(this.Ti(this.clientId), String(Date.now()));\n } catch (t) {\n // Gracefully handle if LocalStorage isn't available / working.\n x(\"Failed to set zombie client id.\", t);\n }\n }\n /** Removes the zombied client entry if it exists. */ Pi() {\n if (this.oi) try {\n this.oi.removeItem(this.Ti(this.clientId));\n } catch (t) {\n // Ignore\n }\n }\n Ti(t) {\n return `firestore_zombie_${this.persistenceKey}_${t}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function Oo(t) {\n return Gi(t, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function Mo(t) {\n return Gi(t, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function Fo(t, e) {\n // Use two different prefix formats:\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let n = t.projectId;\n return t.isDefaultDatabase || (n += \".\" + t.database), \"firestore/\" + e + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nclass $o {\n constructor(t, e, n, s) {\n this.targetId = t, this.fromCache = e, this.Si = n, this.Di = s;\n }\n static Ci(t, e) {\n let n = Es(), s = Es();\n for (const t of e.docChanges) switch (t.type) {\n case 0 /* ChangeType.Added */ :\n n = n.add(t.doc.key);\n break;\n\n case 1 /* ChangeType.Removed */ :\n s = s.add(t.doc.key);\n // do nothing\n }\n return new $o(t, e.fromCache, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */ class Bo {\n constructor() {\n this.xi = !1;\n }\n /** Sets the document view to query against. */ initialize(t, e) {\n this.Ni = t, this.indexManager = e, this.xi = !0;\n }\n /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {\n return this.ki(t, e).next((i => i || this.Oi(t, e, s, n))).next((n => n || this.Mi(t, e)));\n }\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */ ki(t, e) {\n if (fn(e)) \n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return At.resolve(null);\n let n = gn(e);\n return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n e = pn(e, null, \"F\" /* LimitType.First */), n = gn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {\n const i = Es(...s);\n return this.Ni.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {\n const r = this.Fi(e, s);\n return this.$i(e, r, i, n.readTime) ? this.ki(t, pn(e, null, \"F\" /* LimitType.First */)) : this.Bi(t, r, e, n);\n }))));\n })))));\n }\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */ Oi(t, e, n, s) {\n return fn(e) || s.isEqual(st.min()) ? this.Mi(t, e) : this.Ni.getDocuments(t, n).next((i => {\n const r = this.Fi(e, i);\n return this.$i(e, r, n, s) ? this.Mi(t, e) : (S() <= u.DEBUG && C(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", s.toString(), En(e)), \n this.Bi(t, r, e, mt(s, -1)));\n }));\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n }\n /** Applies the query filter and sorting to the provided documents. */ Fi(t, e) {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let n = new We(bn(t));\n return e.forEach(((e, s) => {\n An(t, s) && (n = n.add(s));\n })), n;\n }\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */ $i(t, e, n, s) {\n if (null === t.limit) \n // Queries without limits do not need to be refilled.\n return !1;\n if (n.size !== e.size) \n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return !0;\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const i = \"F\" /* LimitType.First */ === t.limitType ? e.last() : e.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);\n }\n Mi(t, e) {\n return S() <= u.DEBUG && C(\"QueryEngine\", \"Using full collection scan to execute query:\", En(e)), \n this.Ni.getDocumentsMatchingQuery(t, e, yt.min());\n }\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */ Bi(t, e, n, s) {\n // Retrieve all results for documents that were updated since the offset.\n return this.Ni.getDocumentsMatchingQuery(t, n, s).next((t => (\n // Merge with existing results\n e.forEach((e => {\n t = t.insert(e.key, e);\n })), t)));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass Lo {\n constructor(\n /** Manages our in-memory or durable persistence. */\n t, e, n, s) {\n this.persistence = t, this.Li = e, this.yt = s, \n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n this.qi = new Ge(Z), \n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n this.Ui = new ls((t => nn(t)), sn), \n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n this.Ki = new Map, this.Gi = t.getRemoteDocumentCache(), this.Cs = t.getTargetCache(), \n this.Ns = t.getBundleCache(), this.Qi(n);\n }\n Qi(t) {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t), \n this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new po(this.Gi, this.mutationQueue, this.documentOverlayCache, this.indexManager), \n this.Gi.setIndexManager(this.indexManager), this.Li.initialize(this.localDocuments, this.indexManager);\n }\n collectGarbage(t) {\n return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (e => t.collect(e, this.qi)));\n }\n}\n\nfunction qo(\n/** Manages our in-memory or durable persistence. */\nt, e, n, s) {\n return new Lo(t, e, n, s);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function Uo(t, e) {\n const n = $(t);\n return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (t => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let s;\n return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.Qi(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {\n const i = [], r = [];\n // Union the old/new changed keys.\n let o = Es();\n for (const t of s) {\n i.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n for (const t of e) {\n r.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return n.localDocuments.getDocuments(t, o).next((t => ({\n ji: t,\n removedBatchIds: i,\n addedBatchIds: r\n })));\n }));\n }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction Ko(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (t => {\n const s = e.batch.keys(), i = n.Gi.newChangeBuffer({\n trackRemovals: !0\n });\n return function(t, e, n, s) {\n const i = n.batch, r = i.keys();\n let o = At.resolve();\n return r.forEach((t => {\n o = o.next((() => s.getEntry(e, t))).next((e => {\n const r = n.docVersions.get(t);\n M(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n e.setReadTime(n.commitVersion), s.addEntry(e)));\n }));\n })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));\n }\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-Tab only.\n (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {\n let e = Es();\n for (let n = 0; n < t.mutationResults.length; ++n) {\n t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));\n }\n return e;\n }\n /**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));\n }));\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction Go(t) {\n const e = $(t);\n return e.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (t => e.Cs.getLastRemoteSnapshotVersion(t)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function Qo(t, e) {\n const n = $(t), s = e.snapshotVersion;\n let i = n.qi;\n return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (t => {\n const r = n.Gi.newChangeBuffer({\n trackRemovals: !0\n });\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n i = n.qi;\n const o = [];\n e.targetChanges.forEach(((r, u) => {\n const c = i.get(u);\n if (!c) return;\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n o.push(n.Cs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Cs.addMatchingKeys(t, r.addedDocuments, u))));\n let a = c.withSequenceNumber(t.currentSequenceNumber);\n e.targetMismatches.has(u) ? a = a.withResumeToken(Qt.EMPTY_BYTE_STRING, st.min()).withLastLimboFreeSnapshotVersion(st.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)), \n i = i.insert(u, a), \n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n function(t, e, n) {\n // Always persist target data if we don't already have a resume token.\n if (0 === t.resumeToken.approximateByteSize()) return !0;\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n }\n /**\n * Notifies local store of the changed views to locally pin documents.\n */ (c, a, r) && o.push(n.Cs.updateTargetData(t, a));\n }));\n let u = ds(), c = Es();\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (e.documentUpdates.forEach((s => {\n e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));\n })), \n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n o.push(jo(t, r, e.documentUpdates).next((t => {\n u = t.Wi, c = t.zi;\n }))), !s.isEqual(st.min())) {\n const e = n.Cs.getLastRemoteSnapshotVersion(t).next((e => n.Cs.setTargetsMetadata(t, t.currentSequenceNumber, s)));\n o.push(e);\n }\n return At.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));\n })).then((t => (n.qi = i, t)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */ function jo(t, e, n) {\n let s = Es(), i = Es();\n return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {\n let s = ds();\n return n.forEach(((n, r) => {\n const o = t.get(n);\n // Check if see if there is a existence state change for this document.\n r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), \n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n r.isNoDocument() && r.version.isEqual(st.min()) ? (\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r), \n s = s.insert(n, r)) : C(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", o.version, \" Watch version:\", r.version);\n })), {\n Wi: s,\n zi: i\n };\n }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction Wo(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (t => (void 0 === e && (e = -1), \n n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction zo(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (t => {\n let s;\n return n.Cs.getTargetData(t, e).next((i => i ? (\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n s = i, At.resolve(s)) : n.Cs.allocateTargetId(t).next((i => (s = new zi(e, i, 0 /* TargetPurpose.Listen */ , t.currentSequenceNumber), \n n.Cs.addTargetData(t, s).next((() => s)))))));\n })).then((t => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const s = n.qi.get(t.targetId);\n return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.qi = n.qi.insert(t.targetId, t), \n n.Ui.set(e, t.targetId)), t;\n }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function Ho(t, e, n) {\n const s = $(t), i = s.qi.get(e), r = n ? \"readwrite\" : \"readwrite-primary\";\n try {\n n || await s.persistence.runTransaction(\"Release target\", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));\n } catch (t) {\n if (!Vt(t)) throw t;\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n C(\"LocalStore\", `Failed to update sequence numbers for target ${e}: ${t}`);\n }\n s.qi = s.qi.remove(e), s.Ui.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function Jo(t, e, n) {\n const s = $(t);\n let i = st.min(), r = Es();\n return s.persistence.runTransaction(\"Execute query\", \"readonly\", (t => function(t, e, n) {\n const s = $(t), i = s.Ui.get(n);\n return void 0 !== i ? At.resolve(s.qi.get(i)) : s.Cs.getTargetData(e, n);\n }(s, t, gn(e)).next((e => {\n if (e) return i = e.lastLimboFreeSnapshotVersion, s.Cs.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n r = t;\n }));\n })).next((() => s.Li.getDocumentsMatchingQuery(t, e, n ? i : st.min(), n ? r : Es()))).next((t => (Zo(s, Rn(e), t), \n {\n documents: t,\n Hi: r\n })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction Yo(t, e) {\n const n = $(t), s = $(n.Cs), i = n.qi.get(e);\n return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (t => s.ne(t, e).next((t => t ? t.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction Xo(t, e) {\n const n = $(t), s = n.Ki.get(e) || st.min();\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (t => n.Gi.getAllFromCollectionGroup(t, e, mt(s, -1), \n /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (Zo(n, e, t), t)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction Zo(t, e, n) {\n let s = t.Ki.get(e) || st.min();\n n.forEach(((t, e) => {\n e.readTime.compareTo(s) > 0 && (s = e.readTime);\n })), t.Ki.set(e, s);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function tu(t, e, n, s) {\n const i = $(t);\n let r = Es(), o = ds();\n for (const t of n) {\n const n = e.Ji(t.metadata.name);\n t.document && (r = r.add(n));\n const s = e.Yi(t);\n s.setReadTime(e.Xi(t.metadata.readTime)), o = o.insert(n, s);\n }\n const u = i.Gi.newChangeBuffer({\n trackRemovals: !0\n }), c = await zo(i, function(t) {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return gn(ln(rt.fromString(`__bundle__/docs/${t}`)));\n }(s));\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (t => jo(t, u, o).next((e => (u.apply(t), \n e))).next((e => i.Cs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Cs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.Wi, e.zi))).next((() => e.Wi))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function eu(t, e, n = Es()) {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const s = await zo(t, gn(ir(e.bundledQuery))), i = $(t);\n return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (t => {\n const r = qs(e.readTime);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (s.snapshotVersion.compareTo(r) >= 0) return i.Ns.saveNamedQuery(t, e);\n // Update existing target data because the query from the bundle is newer.\n const o = s.withResumeToken(Qt.EMPTY_BYTE_STRING, r);\n return i.qi = i.qi.insert(o.targetId, o), i.Cs.updateTargetData(t, o).next((() => i.Cs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Cs.addMatchingKeys(t, n, s.targetId))).next((() => i.Ns.saveNamedQuery(t, e)));\n }));\n}\n\n/** Assembles the key for a client state in WebStorage */\nfunction nu(t, e) {\n return `firestore_clients_${t}_${e}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations_<persistence_prefix>_<batch_id>\n// (for unauthenticated users)\n// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction su(t, e, n) {\n let s = `firestore_mutations_${t}_${n}`;\n return e.isAuthenticated() && (s += `_${e.uid}`), s;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets_<persistence_prefix>_<target_id>\n/** Assembles the key for a query state in WebStorage */\nfunction iu(t, e) {\n return `firestore_targets_${t}_${e}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_<persistence_prefix>\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass ru {\n constructor(t, e, n, s) {\n this.user = t, this.batchId = e, this.state = n, this.error = s;\n }\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t, e, n) {\n const s = JSON.parse(n);\n let i, r = \"object\" == typeof s && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(s.state) && (void 0 === s.error || \"object\" == typeof s.error);\n return r && s.error && (r = \"string\" == typeof s.error.message && \"string\" == typeof s.error.code, \n r && (i = new L(s.error.code, s.error.message))), r ? new ru(t, e, s.state, i) : (x(\"SharedClientState\", `Failed to parse mutation state for ID '${e}': ${n}`), \n null);\n }\n tr() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass ou {\n constructor(t, e, n) {\n this.targetId = t, this.state = e, this.error = n;\n }\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t, e) {\n const n = JSON.parse(e);\n let s, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n i && (s = new L(n.error.code, n.error.message))), i ? new ou(t, n.state, s) : (x(\"SharedClientState\", `Failed to parse target state for ID '${t}': ${e}`), \n null);\n }\n tr() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class uu {\n constructor(t, e) {\n this.clientId = t, this.activeTargetIds = e;\n }\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t, e) {\n const n = JSON.parse(e);\n let s = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = Rs();\n for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Kt(n.activeTargetIds[t]), \n i = i.add(n.activeTargetIds[t]);\n return s ? new uu(t, i) : (x(\"SharedClientState\", `Failed to parse client data for instance '${t}': ${e}`), \n null);\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class cu {\n constructor(t, e) {\n this.clientId = t, this.onlineState = e;\n }\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t) {\n const e = JSON.parse(t);\n return \"object\" == typeof e && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(e.onlineState) && \"string\" == typeof e.clientId ? new cu(e.clientId, e.onlineState) : (x(\"SharedClientState\", `Failed to parse online state: ${t}`), \n null);\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass au {\n constructor() {\n this.activeTargetIds = Rs();\n }\n er(t) {\n this.activeTargetIds = this.activeTargetIds.add(t);\n }\n nr(t) {\n this.activeTargetIds = this.activeTargetIds.delete(t);\n }\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */ tr() {\n const t = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now()\n };\n return JSON.stringify(t);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class hu {\n constructor(t, e, n, s, i) {\n this.window = t, this.Hs = e, this.persistenceKey = n, this.sr = s, this.syncEngine = null, \n this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ir = this.rr.bind(this), \n this.ur = new Ge(Z), this.started = !1, \n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n this.cr = [];\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const r = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n this.storage = this.window.localStorage, this.currentUser = i, this.ar = nu(this.persistenceKey, this.sr), \n this.hr = \n /** Assembles the key for the current sequence number. */\n function(t) {\n return `firestore_sequence_number_${t}`;\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (this.persistenceKey), this.ur = this.ur.insert(this.sr, new au), this.lr = new RegExp(`^firestore_clients_${r}_([^_]*)$`), \n this.dr = new RegExp(`^firestore_mutations_${r}_(\\\\d+)(?:_(.*))?$`), this._r = new RegExp(`^firestore_targets_${r}_(\\\\d+)$`), \n this.wr = \n /** Assembles the key for the online state of the primary tab. */\n function(t) {\n return `firestore_online_state_${t}`;\n }\n // The WebStorage prefix that plays as a event to indicate the remote documents\n // might have changed due to some secondary tabs loading a bundle.\n // format of the key is:\n // firestore_bundle_loaded_v2_<persistenceKey>\n // The version ending with \"v2\" stores the list of modified collection groups.\n (this.persistenceKey), this.mr = function(t) {\n return `firestore_bundle_loaded_v2_${t}`;\n }\n // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n // looks like 'firestore_sequence_number_<persistence_prefix>'.\n (this.persistenceKey), \n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener(\"storage\", this.ir);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */ static C(t) {\n return !(!t || !t.localStorage);\n }\n async start() {\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const t = await this.syncEngine.vi();\n for (const e of t) {\n if (e === this.sr) continue;\n const t = this.getItem(nu(this.persistenceKey, e));\n if (t) {\n const n = uu.Zi(e, t);\n n && (this.ur = this.ur.insert(n.clientId, n));\n }\n }\n this.gr();\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const e = this.storage.getItem(this.wr);\n if (e) {\n const t = this.yr(e);\n t && this.pr(t);\n }\n for (const t of this.cr) this.rr(t);\n this.cr = [], \n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n }\n writeSequenceNumber(t) {\n this.setItem(this.hr, JSON.stringify(t));\n }\n getAllActiveQueryTargets() {\n return this.Ir(this.ur);\n }\n isActiveQueryTarget(t) {\n let e = !1;\n return this.ur.forEach(((n, s) => {\n s.activeTargetIds.has(t) && (e = !0);\n })), e;\n }\n addPendingMutation(t) {\n this.Tr(t, \"pending\");\n }\n updateMutationState(t, e, n) {\n this.Tr(t, e, n), \n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.Er(t);\n }\n addLocalQueryTarget(t) {\n let e = \"not-current\";\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(t)) {\n const n = this.storage.getItem(iu(this.persistenceKey, t));\n if (n) {\n const s = ou.Zi(t, n);\n s && (e = s.state);\n }\n }\n return this.Ar.er(t), this.gr(), e;\n }\n removeLocalQueryTarget(t) {\n this.Ar.nr(t), this.gr();\n }\n isLocalQueryTarget(t) {\n return this.Ar.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n this.removeItem(iu(this.persistenceKey, t));\n }\n updateQueryState(t, e, n) {\n this.Rr(t, e, n);\n }\n handleUserChange(t, e, n) {\n e.forEach((t => {\n this.Er(t);\n })), this.currentUser = t, n.forEach((t => {\n this.addPendingMutation(t);\n }));\n }\n setOnlineState(t) {\n this.br(t);\n }\n notifyBundleLoaded(t) {\n this.Pr(t);\n }\n shutdown() {\n this.started && (this.window.removeEventListener(\"storage\", this.ir), this.removeItem(this.ar), \n this.started = !1);\n }\n getItem(t) {\n const e = this.storage.getItem(t);\n return C(\"SharedClientState\", \"READ\", t, e), e;\n }\n setItem(t, e) {\n C(\"SharedClientState\", \"SET\", t, e), this.storage.setItem(t, e);\n }\n removeItem(t) {\n C(\"SharedClientState\", \"REMOVE\", t), this.storage.removeItem(t);\n }\n rr(t) {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const e = t;\n if (e.storageArea === this.storage) {\n if (C(\"SharedClientState\", \"EVENT\", e.key, e.newValue), e.key === this.ar) return void x(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n this.Hs.enqueueRetryable((async () => {\n if (this.started) {\n if (null !== e.key) if (this.lr.test(e.key)) {\n if (null == e.newValue) {\n const t = this.vr(e.key);\n return this.Vr(t, null);\n }\n {\n const t = this.Sr(e.key, e.newValue);\n if (t) return this.Vr(t.clientId, t);\n }\n } else if (this.dr.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Dr(e.key, e.newValue);\n if (t) return this.Cr(t);\n }\n } else if (this._r.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Nr(e.key, e.newValue);\n if (t) return this.kr(t);\n }\n } else if (e.key === this.wr) {\n if (null !== e.newValue) {\n const t = this.yr(e.newValue);\n if (t) return this.pr(t);\n }\n } else if (e.key === this.hr) {\n const t = function(t) {\n let e = Ot.at;\n if (null != t) try {\n const n = JSON.parse(t);\n M(\"number\" == typeof n), e = n;\n } catch (t) {\n x(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", t);\n }\n return e;\n }\n /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (e.newValue);\n t !== Ot.at && this.sequenceNumberHandler(t);\n } else if (e.key === this.mr) {\n const t = this.Or(e.newValue);\n await Promise.all(t.map((t => this.syncEngine.Mr(t))));\n }\n } else this.cr.push(e);\n }));\n }\n }\n get Ar() {\n return this.ur.get(this.sr);\n }\n gr() {\n this.setItem(this.ar, this.Ar.tr());\n }\n Tr(t, e, n) {\n const s = new ru(this.currentUser, t, e, n), i = su(this.persistenceKey, this.currentUser, t);\n this.setItem(i, s.tr());\n }\n Er(t) {\n const e = su(this.persistenceKey, this.currentUser, t);\n this.removeItem(e);\n }\n br(t) {\n const e = {\n clientId: this.sr,\n onlineState: t\n };\n this.storage.setItem(this.wr, JSON.stringify(e));\n }\n Rr(t, e, n) {\n const s = iu(this.persistenceKey, t), i = new ou(t, e, n);\n this.setItem(s, i.tr());\n }\n Pr(t) {\n const e = JSON.stringify(Array.from(t));\n this.setItem(this.mr, e);\n }\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */ vr(t) {\n const e = this.lr.exec(t);\n return e ? e[1] : null;\n }\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */ Sr(t, e) {\n const n = this.vr(t);\n return uu.Zi(n, e);\n }\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Dr(t, e) {\n const n = this.dr.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n return ru.Zi(new P(i), s, e);\n }\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Nr(t, e) {\n const n = this._r.exec(t), s = Number(n[1]);\n return ou.Zi(s, e);\n }\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ yr(t) {\n return cu.Zi(t);\n }\n Or(t) {\n return JSON.parse(t);\n }\n async Cr(t) {\n if (t.user.uid === this.currentUser.uid) return this.syncEngine.Fr(t.batchId, t.state, t.error);\n C(\"SharedClientState\", `Ignoring mutation for non-active user ${t.user.uid}`);\n }\n kr(t) {\n return this.syncEngine.$r(t.targetId, t.state, t.error);\n }\n Vr(t, e) {\n const n = e ? this.ur.insert(t, e) : this.ur.remove(t), s = this.Ir(this.ur), i = this.Ir(n), r = [], o = [];\n return i.forEach((t => {\n s.has(t) || r.push(t);\n })), s.forEach((t => {\n i.has(t) || o.push(t);\n })), this.syncEngine.Br(r, o).then((() => {\n this.ur = n;\n }));\n }\n pr(t) {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n this.ur.get(t.clientId) && this.onlineStateHandler(t.onlineState);\n }\n Ir(t) {\n let e = Rs();\n return t.forEach(((t, n) => {\n e = e.unionWith(n.activeTargetIds);\n })), e;\n }\n}\n\nclass lu {\n constructor() {\n this.Lr = new au, this.qr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;\n }\n addPendingMutation(t) {\n // No op.\n }\n updateMutationState(t, e, n) {\n // No op.\n }\n addLocalQueryTarget(t) {\n return this.Lr.er(t), this.qr[t] || \"not-current\";\n }\n updateQueryState(t, e, n) {\n this.qr[t] = e;\n }\n removeLocalQueryTarget(t) {\n this.Lr.nr(t);\n }\n isLocalQueryTarget(t) {\n return this.Lr.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n delete this.qr[t];\n }\n getAllActiveQueryTargets() {\n return this.Lr.activeTargetIds;\n }\n isActiveQueryTarget(t) {\n return this.Lr.activeTargetIds.has(t);\n }\n start() {\n return this.Lr = new au, Promise.resolve();\n }\n handleUserChange(t, e, n) {\n // No op.\n }\n setOnlineState(t) {\n // No op.\n }\n shutdown() {}\n writeSequenceNumber(t) {}\n notifyBundleLoaded(t) {\n // No op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class fu {\n Ur(t) {\n // No-op.\n }\n shutdown() {\n // No-op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass du {\n constructor() {\n this.Kr = () => this.Gr(), this.Qr = () => this.jr(), this.Wr = [], this.zr();\n }\n Ur(t) {\n this.Wr.push(t);\n }\n shutdown() {\n window.removeEventListener(\"online\", this.Kr), window.removeEventListener(\"offline\", this.Qr);\n }\n zr() {\n window.addEventListener(\"online\", this.Kr), window.addEventListener(\"offline\", this.Qr);\n }\n Gr() {\n C(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n for (const t of this.Wr) t(0 /* NetworkStatus.AVAILABLE */);\n }\n jr() {\n C(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n for (const t of this.Wr) t(1 /* NetworkStatus.UNAVAILABLE */);\n }\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static C() {\n return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const _u = {\n BatchGetDocuments: \"batchGet\",\n Commit: \"commit\",\n RunQuery: \"runQuery\",\n RunAggregationQuery: \"runAggregationQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass wu {\n constructor(t) {\n this.Hr = t.Hr, this.Jr = t.Jr;\n }\n Yr(t) {\n this.Xr = t;\n }\n Zr(t) {\n this.eo = t;\n }\n onMessage(t) {\n this.no = t;\n }\n close() {\n this.Jr();\n }\n send(t) {\n this.Hr(t);\n }\n so() {\n this.Xr();\n }\n io(t) {\n this.eo(t);\n }\n ro(t) {\n this.no(t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class mu extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass {\n constructor(t) {\n this.databaseInfo = t, this.databaseId = t.databaseId;\n const e = t.ssl ? \"https\" : \"http\";\n this.oo = e + \"://\" + t.host, this.uo = \"projects/\" + this.databaseId.projectId + \"/databases/\" + this.databaseId.database + \"/documents\";\n }\n get co() {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return !1;\n }\n ao(t, e, n, s, i) {\n const r = this.ho(t, e);\n C(\"RestConnection\", \"Sending: \", r, n);\n const o = {};\n return this.lo(o, s, i), this.fo(t, r, o, n).then((t => (C(\"RestConnection\", \"Received: \", t), \n t)), (e => {\n throw N(\"RestConnection\", `${t} failed with error: `, e, \"url: \", r, \"request:\", n), \n e;\n }));\n }\n _o(t, e, n, s, i, r) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.ao(t, e, n, s, i);\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */ lo(t, e, n) {\n t[\"X-Goog-Api-Client\"] = \"gl-js/ fire/\" + v, \n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n t[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (t[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));\n }\n ho(t, e) {\n const n = _u[t];\n return `${this.oo}/v1/${e}:${n}`;\n }\n} {\n constructor(t) {\n super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling, \n this.useFetchStreams = t.useFetchStreams;\n }\n fo(t, e, n, s) {\n return new Promise(((i, r) => {\n const o = new m;\n o.setWithCredentials(!0), o.listenOnce(g.COMPLETE, (() => {\n try {\n switch (o.getLastErrorCode()) {\n case y.NO_ERROR:\n const e = o.getResponseJson();\n C(\"Connection\", \"XHR received:\", JSON.stringify(e)), i(e);\n break;\n\n case y.TIMEOUT:\n C(\"Connection\", 'RPC \"' + t + '\" timed out'), r(new L(B.DEADLINE_EXCEEDED, \"Request time out\"));\n break;\n\n case y.HTTP_ERROR:\n const n = o.getStatus();\n if (C(\"Connection\", 'RPC \"' + t + '\" failed with status:', n, \"response text:\", o.getResponseText()), \n n > 0) {\n let t = o.getResponseJson();\n Array.isArray(t) && (t = t[0]);\n const e = null == t ? void 0 : t.error;\n if (e && e.status && e.message) {\n const t = function(t) {\n const e = t.toLowerCase().replace(/_/g, \"-\");\n return Object.values(B).indexOf(e) >= 0 ? e : B.UNKNOWN;\n }(e.status);\n r(new L(t, e.message));\n } else r(new L(B.UNKNOWN, \"Server responded with status \" + o.getStatus()));\n } else \n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n r(new L(B.UNAVAILABLE, \"Connection failed.\"));\n break;\n\n default:\n O();\n }\n } finally {\n C(\"Connection\", 'RPC \"' + t + '\" completed.');\n }\n }));\n const u = JSON.stringify(s);\n o.send(e, \"POST\", u, n, 15);\n }));\n }\n wo(t, e, n) {\n const s = [ this.oo, \"/\", \"google.firestore.v1.Firestore\", \"/\", t, \"/channel\" ], i = p(), r = I(), o = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: \"gsessionid\",\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: !0,\n supportsCrossDomainXhr: !0,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 6e5\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n this.useFetchStreams && (o.xmlHttpFactory = new T({})), this.lo(o.initMessageHeaders, e, n), \n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n o.encodeInitMessageHeaders = !0;\n const u = s.join(\"\");\n C(\"Connection\", \"Creating WebChannel: \" + u, o);\n const c = i.createWebChannel(u, o);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let a = !1, h = !1;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n const l = new wu({\n Hr: t => {\n h ? C(\"Connection\", \"Not sending because WebChannel is closed:\", t) : (a || (C(\"Connection\", \"Opening WebChannel transport.\"), \n c.open(), a = !0), C(\"Connection\", \"WebChannel sending:\", t), c.send(t));\n },\n Jr: () => c.close()\n }), f = (t, e, n) => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n t.listen(e, (t => {\n try {\n n(t);\n } catch (t) {\n setTimeout((() => {\n throw t;\n }), 0);\n }\n }));\n };\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n return f(c, E.EventType.OPEN, (() => {\n h || C(\"Connection\", \"WebChannel transport opened.\");\n })), f(c, E.EventType.CLOSE, (() => {\n h || (h = !0, C(\"Connection\", \"WebChannel transport closed\"), l.io());\n })), f(c, E.EventType.ERROR, (t => {\n h || (h = !0, N(\"Connection\", \"WebChannel transport errored:\", t), l.io(new L(B.UNAVAILABLE, \"The operation could not be completed\")));\n })), f(c, E.EventType.MESSAGE, (t => {\n var e;\n if (!h) {\n const n = t.data[0];\n M(!!n);\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const s = n, i = s.error || (null === (e = s[0]) || void 0 === e ? void 0 : e.error);\n if (i) {\n C(\"Connection\", \"WebChannel received error:\", i);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const t = i.status;\n let e = \n /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\n function(t) {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = us[t];\n if (void 0 !== e) return hs(e);\n }(t), n = i.message;\n void 0 === e && (e = B.INTERNAL, n = \"Unknown error status: \" + t + \" with message \" + i.message), \n // Mark closed so no further events are propagated\n h = !0, l.io(new L(e, n)), c.close();\n } else C(\"Connection\", \"WebChannel received:\", n), l.ro(n);\n }\n })), f(r, A.STAT_EVENT, (t => {\n t.stat === R.PROXY ? C(\"Connection\", \"Detected buffering proxy\") : t.stat === R.NOPROXY && C(\"Connection\", \"Detected no buffering proxy\");\n })), setTimeout((() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n l.so();\n }), 0), l;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Initializes the WebChannelConnection for the browser. */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The Platform's 'window' implementation or null if not available. */\nfunction gu() {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function yu() {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof document ? document : null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function pu(t) {\n return new Fs(t, /* useProto3Json= */ !0);\n}\n\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass Iu {\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n t, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n e, \n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n n = 1e3\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */ , s = 1.5\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */ , i = 6e4) {\n this.Hs = t, this.timerId = e, this.mo = n, this.yo = s, this.po = i, this.Io = 0, \n this.To = null, \n /** The last backoff attempt, as epoch milliseconds. */\n this.Eo = Date.now(), this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */ reset() {\n this.Io = 0;\n }\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */ Ao() {\n this.Io = this.po;\n }\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */ Ro(t) {\n // Cancel any pending backoff operation.\n this.cancel();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const e = Math.floor(this.Io + this.bo()), n = Math.max(0, Date.now() - this.Eo), s = Math.max(0, e - n);\n // Guard against lastAttemptTime being in the future due to a clock change.\n s > 0 && C(\"ExponentialBackoff\", `Backing off for ${s} ms (base delay: ${this.Io} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), \n this.To = this.Hs.enqueueAfterDelay(this.timerId, s, (() => (this.Eo = Date.now(), \n t()))), \n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.Io *= this.yo, this.Io < this.mo && (this.Io = this.mo), this.Io > this.po && (this.Io = this.po);\n }\n Po() {\n null !== this.To && (this.To.skipDelay(), this.To = null);\n }\n cancel() {\n null !== this.To && (this.To.cancel(), this.To = null);\n }\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ bo() {\n return (Math.random() - .5) * this.Io;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nclass Tu {\n constructor(t, e, n, s, i, r, o, u) {\n this.Hs = t, this.vo = n, this.Vo = s, this.connection = i, this.authCredentialsProvider = r, \n this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ , \n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n this.So = 0, this.Do = null, this.Co = null, this.stream = null, this.xo = new Iu(t, e);\n }\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */ No() {\n return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.ko();\n }\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */ ko() {\n return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;\n }\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */ start() {\n 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Oo();\n }\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */ async stop() {\n this.No() && await this.close(0 /* PersistentStreamState.Initial */);\n }\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */ Mo() {\n this.state = 0 /* PersistentStreamState.Initial */ , this.xo.reset();\n }\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */ Fo() {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n this.ko() && null === this.Do && (this.Do = this.Hs.enqueueAfterDelay(this.vo, 6e4, (() => this.$o())));\n }\n /** Sends a message to the underlying stream. */ Bo(t) {\n this.Lo(), this.stream.send(t);\n }\n /** Called by the idle timer when the stream should close due to inactivity. */ async $o() {\n if (this.ko()) \n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(0 /* PersistentStreamState.Initial */);\n }\n /** Marks the stream as active again. */ Lo() {\n this.Do && (this.Do.cancel(), this.Do = null);\n }\n /** Cancels the health check delayed operation. */ qo() {\n this.Co && (this.Co.cancel(), this.Co = null);\n }\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */ async close(t, e) {\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.Lo(), this.qo(), this.xo.cancel(), \n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.So++, 4 /* PersistentStreamState.Error */ !== t ? \n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.xo.reset() : e && e.code === B.RESOURCE_EXHAUSTED ? (\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n x(e.toString()), x(\"Using maximum backoff delay to prevent overloading the backend.\"), \n this.xo.Ao()) : e && e.code === B.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n // Clean up the underlying stream because we are no longer interested in events.\n null !== this.stream && (this.Uo(), this.stream.close(), this.stream = null), \n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = t, \n // Notify the listener that the stream closed.\n await this.listener.Zr(e);\n }\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */ Uo() {}\n auth() {\n this.state = 1 /* PersistentStreamState.Starting */;\n const t = this.Ko(this.So), e = this.So;\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n this.So === e && \n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.Go(t, n);\n }), (e => {\n t((() => {\n const t = new L(B.UNKNOWN, \"Fetching auth token failed: \" + e.message);\n return this.Qo(t);\n }));\n }));\n }\n Go(t, e) {\n const n = this.Ko(this.So);\n this.stream = this.jo(t, e), this.stream.Yr((() => {\n n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Co = this.Hs.enqueueAfterDelay(this.Vo, 1e4, (() => (this.ko() && (this.state = 3 /* PersistentStreamState.Healthy */), \n Promise.resolve()))), this.listener.Yr())));\n })), this.stream.Zr((t => {\n n((() => this.Qo(t)));\n })), this.stream.onMessage((t => {\n n((() => this.onMessage(t)));\n }));\n }\n Oo() {\n this.state = 5 /* PersistentStreamState.Backoff */ , this.xo.Ro((async () => {\n this.state = 0 /* PersistentStreamState.Initial */ , this.start();\n }));\n }\n // Visible for tests\n Qo(t) {\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return C(\"PersistentStream\", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);\n }\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */ Ko(t) {\n return e => {\n this.Hs.enqueueAndForget((() => this.So === t ? e() : (C(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n Promise.resolve())));\n };\n }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class Eu extends Tu {\n constructor(t, e, n, s, i, r) {\n super(t, \"listen_stream_connection_backoff\" /* TimerId.ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* TimerId.ListenStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , e, n, s, r), \n this.yt = i;\n }\n jo(t, e) {\n return this.connection.wo(\"Listen\", t, e);\n }\n onMessage(t) {\n // A successful response means the stream is healthy\n this.xo.reset();\n const e = Zs(this.yt, t), n = function(t) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!(\"targetChange\" in t)) return st.min();\n const e = t.targetChange;\n return e.targetIds && e.targetIds.length ? st.min() : e.readTime ? qs(e.readTime) : st.min();\n }(t);\n return this.listener.Wo(e, n);\n }\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */ zo(t) {\n const e = {};\n e.database = zs(this.yt), e.addTarget = function(t, e) {\n let n;\n const s = e.target;\n return n = rn(s) ? {\n documents: si(t, s)\n } : {\n query: ii(t, s)\n }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? n.resumeToken = Bs(t, e.resumeToken) : e.snapshotVersion.compareTo(st.min()) > 0 && (\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n n.readTime = $s(t, e.snapshotVersion.toTimestamp())), n;\n }(this.yt, t);\n const n = oi(this.yt, t);\n n && (e.labels = n), this.Bo(e);\n }\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */ Ho(t) {\n const e = {};\n e.database = zs(this.yt), e.removeTarget = t, this.Bo(e);\n }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class Au extends Tu {\n constructor(t, e, n, s, i, r) {\n super(t, \"write_stream_connection_backoff\" /* TimerId.WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* TimerId.WriteStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , e, n, s, r), \n this.yt = i, this.Jo = !1;\n }\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */ get Yo() {\n return this.Jo;\n }\n // Override of PersistentStream.start\n start() {\n this.Jo = !1, this.lastStreamToken = void 0, super.start();\n }\n Uo() {\n this.Jo && this.Xo([]);\n }\n jo(t, e) {\n return this.connection.wo(\"Write\", t, e);\n }\n onMessage(t) {\n if (\n // Always capture the last stream token.\n M(!!t.streamToken), this.lastStreamToken = t.streamToken, this.Jo) {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.xo.reset();\n const e = ni(t.writeResults, t.commitTime), n = qs(t.commitTime);\n return this.listener.Zo(n, e);\n }\n // The first response is always the handshake response\n return M(!t.writeResults || 0 === t.writeResults.length), this.Jo = !0, this.listener.tu();\n }\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */ eu() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const t = {};\n t.database = zs(this.yt), this.Bo(t);\n }\n /** Sends a group of mutations to the Firestore backend to apply. */ Xo(t) {\n const e = {\n streamToken: this.lastStreamToken,\n writes: t.map((t => ti(this.yt, t)))\n };\n this.Bo(e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass Ru extends class {} {\n constructor(t, e, n, s) {\n super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n, \n this.yt = s, this.nu = !1;\n }\n su() {\n if (this.nu) throw new L(B.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n /** Invokes the provided RPC with auth and AppCheck tokens. */ ao(t, e, n) {\n return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.ao(t, e, n, s, i))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === B.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new L(B.UNKNOWN, t.toString());\n }));\n }\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ _o(t, e, n, s) {\n return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection._o(t, e, n, i, r, s))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === B.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new L(B.UNKNOWN, t.toString());\n }));\n }\n terminate() {\n this.nu = !0;\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nasync function bu(t, e) {\n const n = $(t), s = function(t, e) {\n const n = ii(t, e);\n return {\n structuredAggregationQuery: {\n aggregations: [ {\n count: {},\n alias: \"count_alias\"\n } ],\n structuredQuery: n.structuredQuery\n },\n parent: n.parent\n };\n }(n.yt, gn(e)), i = s.parent;\n n.connection.co || delete s.parent;\n return (await n._o(\"RunAggregationQuery\", i, s, /*expectedResponseCount=*/ 1)).filter((t => !!t.result)).map((t => t.result.aggregateFields));\n}\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass Pu {\n constructor(t, e) {\n this.asyncQueue = t, this.onlineStateHandler = e, \n /** The current OnlineState. */\n this.state = \"Unknown\" /* OnlineState.Unknown */ , \n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n this.iu = 0, \n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n this.ru = null, \n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n this.ou = !0;\n }\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */ uu() {\n 0 === this.iu && (this.cu(\"Unknown\" /* OnlineState.Unknown */), this.ru = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.ru = null, \n this.au(\"Backend didn't respond within 10 seconds.\"), this.cu(\"Offline\" /* OnlineState.Offline */), \n Promise.resolve()))));\n }\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */ hu(t) {\n \"Online\" /* OnlineState.Online */ === this.state ? this.cu(\"Unknown\" /* OnlineState.Unknown */) : (this.iu++, \n this.iu >= 1 && (this.lu(), this.au(`Connection failed 1 times. Most recent error: ${t.toString()}`), \n this.cu(\"Offline\" /* OnlineState.Offline */)));\n }\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */ set(t) {\n this.lu(), this.iu = 0, \"Online\" /* OnlineState.Online */ === t && (\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.ou = !1), this.cu(t);\n }\n cu(t) {\n t !== this.state && (this.state = t, this.onlineStateHandler(t));\n }\n au(t) {\n const e = `Could not reach Cloud Firestore backend. ${t}\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;\n this.ou ? (x(e), this.ou = !1) : C(\"OnlineStateTracker\", e);\n }\n lu() {\n null !== this.ru && (this.ru.cancel(), this.ru = null);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class vu {\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n t, \n /** The client-side proxy for interacting with the backend. */\n e, n, s, i) {\n this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {}, \n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n this.fu = [], \n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.du = new Map, \n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n this._u = new Set, \n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n this.wu = [], this.mu = i, this.mu.Ur((t => {\n n.enqueueAndForget((async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n Mu(this) && (C(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n await async function(t) {\n const e = $(t);\n e._u.add(4 /* OfflineCause.ConnectivityChange */), await Su(e), e.gu.set(\"Unknown\" /* OnlineState.Unknown */), \n e._u.delete(4 /* OfflineCause.ConnectivityChange */), await Vu(e);\n }(this));\n }));\n })), this.gu = new Pu(n, s);\n }\n}\n\nasync function Vu(t) {\n if (Mu(t)) for (const e of t.wu) await e(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function Su(t) {\n for (const e of t.wu) await e(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction Du(t, e) {\n const n = $(t);\n n.du.has(e.targetId) || (\n // Mark this as something the client is currently listening for.\n n.du.set(e.targetId, e), Ou(n) ? \n // The listen will be sent in onWatchStreamOpen\n ku(n) : tc(n).ko() && xu(n, e));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function Cu(t, e) {\n const n = $(t), s = tc(n);\n n.du.delete(e), s.ko() && Nu(n, e), 0 === n.du.size && (s.ko() ? s.Fo() : Mu(n) && \n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n n.gu.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function xu(t, e) {\n t.yu.Ot(e.targetId), tc(t).zo(e);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function Nu(t, e) {\n t.yu.Ot(e), tc(t).Ho(e);\n}\n\nfunction ku(t) {\n t.yu = new Cs({\n getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),\n ne: e => t.du.get(e) || null\n }), tc(t).start(), t.gu.uu();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function Ou(t) {\n return Mu(t) && !tc(t).No() && t.du.size > 0;\n}\n\nfunction Mu(t) {\n return 0 === $(t)._u.size;\n}\n\nfunction Fu(t) {\n t.yu = void 0;\n}\n\nasync function $u(t) {\n t.du.forEach(((e, n) => {\n xu(t, e);\n }));\n}\n\nasync function Bu(t, e) {\n Fu(t), \n // If we still need the watch stream, retry the connection.\n Ou(t) ? (t.gu.hu(e), ku(t)) : \n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n t.gu.set(\"Unknown\" /* OnlineState.Unknown */);\n}\n\nasync function Lu(t, e, n) {\n if (\n // Mark the client as online since we got a message from the server\n t.gu.set(\"Online\" /* OnlineState.Online */), e instanceof Ss && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause) \n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await \n /** Handles an error on a target */\n async function(t, e) {\n const n = e.cause;\n for (const s of e.targetIds) \n // A watched target might have been removed already.\n t.du.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.du.delete(s), t.yu.removeTarget(s));\n }\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (t, e);\n } catch (n) {\n C(\"RemoteStore\", \"Failed to remove targets %s: %s \", e.targetIds.join(\",\"), n), \n await qu(t, n);\n } else if (e instanceof vs ? t.yu.Kt(e) : e instanceof Vs ? t.yu.Jt(e) : t.yu.jt(e), \n !n.isEqual(st.min())) try {\n const e = await Go(t.localStore);\n n.compareTo(e) >= 0 && \n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await \n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n function(t, e) {\n const n = t.yu.Zt(e);\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n return n.targetChanges.forEach(((n, s) => {\n if (n.resumeToken.approximateByteSize() > 0) {\n const i = t.du.get(s);\n // A watched target might have been removed already.\n i && t.du.set(s, i.withResumeToken(n.resumeToken, e));\n }\n })), \n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n n.targetMismatches.forEach((e => {\n const n = t.du.get(e);\n if (!n) \n // A watched target might have been removed already.\n return;\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n t.du.set(e, n.withResumeToken(Qt.EMPTY_BYTE_STRING, n.snapshotVersion)), \n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n Nu(t, e);\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const s = new zi(n.target, e, 1 /* TargetPurpose.ExistenceFilterMismatch */ , n.sequenceNumber);\n xu(t, s);\n })), t.remoteSyncer.applyRemoteEvent(n);\n }(t, n);\n } catch (e) {\n C(\"RemoteStore\", \"Failed to raise snapshot:\", e), await qu(t, e);\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function qu(t, e, n) {\n if (!Vt(e)) throw e;\n t._u.add(1 /* OfflineCause.IndexedDbFailed */), \n // Disable network and raise offline snapshots\n await Su(t), t.gu.set(\"Offline\" /* OnlineState.Offline */), n || (\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n n = () => Go(t.localStore)), \n // Probe IndexedDB periodically and re-enable network\n t.asyncQueue.enqueueRetryable((async () => {\n C(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), t._u.delete(1 /* OfflineCause.IndexedDbFailed */), \n await Vu(t);\n }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function Uu(t, e) {\n return e().catch((n => qu(t, n, e)));\n}\n\nasync function Ku(t) {\n const e = $(t), n = ec(e);\n let s = e.fu.length > 0 ? e.fu[e.fu.length - 1].batchId : -1;\n for (;Gu(e); ) try {\n const t = await Wo(e.localStore, s);\n if (null === t) {\n 0 === e.fu.length && n.Fo();\n break;\n }\n s = t.batchId, Qu(e, t);\n } catch (t) {\n await qu(e, t);\n }\n ju(e) && Wu(e);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function Gu(t) {\n return Mu(t) && t.fu.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function Qu(t, e) {\n t.fu.push(e);\n const n = ec(t);\n n.ko() && n.Yo && n.Xo(e.mutations);\n}\n\nfunction ju(t) {\n return Mu(t) && !ec(t).No() && t.fu.length > 0;\n}\n\nfunction Wu(t) {\n ec(t).start();\n}\n\nasync function zu(t) {\n ec(t).eu();\n}\n\nasync function Hu(t) {\n const e = ec(t);\n // Send the write pipeline now that the stream is established.\n for (const n of t.fu) e.Xo(n.mutations);\n}\n\nasync function Ju(t, e, n) {\n const s = t.fu.shift(), i = ji.from(s, e, n);\n await Uu(t, (() => t.remoteSyncer.applySuccessfulWrite(i))), \n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await Ku(t);\n}\n\nasync function Yu(t, e) {\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n e && ec(t).Yo && \n // This error affects the actual write.\n await async function(t, e) {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (n = e.code, as(n) && n !== B.ABORTED) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const n = t.fu.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n ec(t).Mo(), await Uu(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))), \n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await Ku(t);\n }\n var n;\n }(t, e), \n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n ju(t) && Wu(t);\n}\n\nasync function Xu(t, e) {\n const n = $(t);\n n.asyncQueue.verifyOperationInProgress(), C(\"RemoteStore\", \"RemoteStore received new credentials\");\n const s = Mu(n);\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n n._u.add(3 /* OfflineCause.CredentialChange */), await Su(n), s && \n // Don't set the network status to Unknown if we are offline.\n n.gu.set(\"Unknown\" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e), \n n._u.delete(3 /* OfflineCause.CredentialChange */), await Vu(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function Zu(t, e) {\n const n = $(t);\n e ? (n._u.delete(2 /* OfflineCause.IsSecondary */), await Vu(n)) : e || (n._u.add(2 /* OfflineCause.IsSecondary */), \n await Su(n), n.gu.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function tc(t) {\n return t.pu || (\n // Create stream (but note that it is not started yet).\n t.pu = function(t, e, n) {\n const s = $(t);\n return s.su(), new Eu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.datastore, t.asyncQueue, {\n Yr: $u.bind(null, t),\n Zr: Bu.bind(null, t),\n Wo: Lu.bind(null, t)\n }), t.wu.push((async e => {\n e ? (t.pu.Mo(), Ou(t) ? ku(t) : t.gu.set(\"Unknown\" /* OnlineState.Unknown */)) : (await t.pu.stop(), \n Fu(t));\n }))), t.pu;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function ec(t) {\n return t.Iu || (\n // Create stream (but note that it is not started yet).\n t.Iu = function(t, e, n) {\n const s = $(t);\n return s.su(), new Au(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);\n }(t.datastore, t.asyncQueue, {\n Yr: zu.bind(null, t),\n Zr: Yu.bind(null, t),\n tu: Hu.bind(null, t),\n Zo: Ju.bind(null, t)\n }), t.wu.push((async e => {\n e ? (t.Iu.Mo(), \n // This will start the write stream if necessary.\n await Ku(t)) : (await t.Iu.stop(), t.fu.length > 0 && (C(\"RemoteStore\", `Stopping write stream with ${t.fu.length} pending writes`), \n t.fu = []));\n }))), t.Iu;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass nc {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i, \n this.deferred = new q, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch((t => {}));\n }\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */ static createAndSchedule(t, e, n, s, i) {\n const r = Date.now() + n, o = new nc(t, e, r, s, i);\n return o.start(n), o;\n }\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */ start(t) {\n this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);\n }\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */ skipDelay() {\n return this.handleDelayElapsed();\n }\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */ cancel(t) {\n null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new L(B.CANCELLED, \"Operation cancelled\" + (t ? \": \" + t : \"\"))));\n }\n handleDelayElapsed() {\n this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));\n }\n clearTimeout() {\n null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n this.timerHandle = null);\n }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function sc(t, e) {\n if (x(\"AsyncQueue\", `${e}: ${t}`), Vt(t)) return new L(B.UNAVAILABLE, `${e}: ${t}`);\n throw t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class ic {\n /** The default ordering is by key if the comparator is omitted */\n constructor(t) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n this.comparator = t ? (e, n) => t(e, n) || ct.comparator(e.key, n.key) : (t, e) => ct.comparator(t.key, e.key), \n this.keyedMap = ws(), this.sortedSet = new Ge(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */ static emptySet(t) {\n return new ic(t.comparator);\n }\n has(t) {\n return null != this.keyedMap.get(t);\n }\n get(t) {\n return this.keyedMap.get(t);\n }\n first() {\n return this.sortedSet.minKey();\n }\n last() {\n return this.sortedSet.maxKey();\n }\n isEmpty() {\n return this.sortedSet.isEmpty();\n }\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */ indexOf(t) {\n const e = this.keyedMap.get(t);\n return e ? this.sortedSet.indexOf(e) : -1;\n }\n get size() {\n return this.sortedSet.size;\n }\n /** Iterates documents in order defined by \"comparator\" */ forEach(t) {\n this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Inserts or updates a document with the same key */ add(t) {\n // First remove the element if we have it.\n const e = this.delete(t.key);\n return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));\n }\n /** Deletes a document with a given key */ delete(t) {\n const e = this.get(t);\n return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;\n }\n isEqual(t) {\n if (!(t instanceof ic)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (!t.isEqual(s)) return !1;\n }\n return !0;\n }\n toString() {\n const t = [];\n return this.forEach((e => {\n t.push(e.toString());\n })), 0 === t.length ? \"DocumentSet ()\" : \"DocumentSet (\\n \" + t.join(\" \\n\") + \"\\n)\";\n }\n copy(t, e) {\n const n = new ic;\n return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class rc {\n constructor() {\n this.Tu = new Ge(ct.comparator);\n }\n track(t) {\n const e = t.doc.key, n = this.Tu.get(e);\n n ? \n // Merge the new change with the existing change.\n 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Tu = this.Tu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Tu = this.Tu.insert(e, {\n type: n.type,\n doc: t.doc\n }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 2 /* ChangeType.Modified */ ,\n doc: t.doc\n }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 0 /* ChangeType.Added */ ,\n doc: t.doc\n }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 1 /* ChangeType.Removed */ ,\n doc: n.doc\n }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 2 /* ChangeType.Modified */ ,\n doc: t.doc\n }) : \n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n O() : this.Tu = this.Tu.insert(e, t);\n }\n Eu() {\n const t = [];\n return this.Tu.inorderTraversal(((e, n) => {\n t.push(n);\n })), t;\n }\n}\n\nclass oc {\n constructor(t, e, n, s, i, r, o, u, c) {\n this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i, \n this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u, \n this.hasCachedResults = c;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {\n const r = [];\n return e.forEach((t => {\n r.push({\n type: 0 /* ChangeType.Added */ ,\n doc: t\n });\n })), new oc(t, e, ic.emptySet(e), r, n, s, \n /* syncStateChanged= */ !0, \n /* excludesMetadataChanges= */ !1, i);\n }\n get hasPendingWrites() {\n return !this.mutatedKeys.isEmpty();\n }\n isEqual(t) {\n if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && In(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;\n const e = this.docChanges, n = t.docChanges;\n if (e.length !== n.length) return !1;\n for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;\n return !0;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class uc {\n constructor() {\n this.Au = void 0, this.listeners = [];\n }\n}\n\nclass cc {\n constructor() {\n this.queries = new ls((t => Tn(t)), In), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.Ru = new Set;\n }\n}\n\nasync function ac(t, e) {\n const n = $(t), s = e.query;\n let i = !1, r = n.queries.get(s);\n if (r || (i = !0, r = new uc), i) try {\n r.Au = await n.onListen(s);\n } catch (t) {\n const n = sc(t, `Initialization of query '${En(e.query)}' failed`);\n return void e.onError(n);\n }\n if (n.queries.set(s, r), r.listeners.push(e), \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n e.bu(n.onlineState), r.Au) {\n e.Pu(r.Au) && dc(n);\n }\n}\n\nasync function hc(t, e) {\n const n = $(t), s = e.query;\n let i = !1;\n const r = n.queries.get(s);\n if (r) {\n const t = r.listeners.indexOf(e);\n t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);\n }\n if (i) return n.queries.delete(s), n.onUnlisten(s);\n}\n\nfunction lc(t, e) {\n const n = $(t);\n let s = !1;\n for (const t of e) {\n const e = t.query, i = n.queries.get(e);\n if (i) {\n for (const e of i.listeners) e.Pu(t) && (s = !0);\n i.Au = t;\n }\n }\n s && dc(n);\n}\n\nfunction fc(t, e, n) {\n const s = $(t), i = s.queries.get(e);\n if (i) for (const t of i.listeners) t.onError(n);\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n s.queries.delete(e);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction dc(t) {\n t.Ru.forEach((t => {\n t.next();\n }));\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */ class _c {\n constructor(t, e, n) {\n this.query = t, this.vu = e, \n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.Vu = !1, this.Su = null, this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.options = n || {};\n }\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */ Pu(t) {\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const e = [];\n for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);\n t = new oc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged, \n /* excludesMetadataChanges= */ !0, t.hasCachedResults);\n }\n let e = !1;\n return this.Vu ? this.Du(t) && (this.vu.next(t), e = !0) : this.Cu(t, this.onlineState) && (this.xu(t), \n e = !0), this.Su = t, e;\n }\n onError(t) {\n this.vu.error(t);\n }\n /** Returns whether a snapshot was raised. */ bu(t) {\n this.onlineState = t;\n let e = !1;\n return this.Su && !this.Vu && this.Cu(this.Su, t) && (this.xu(this.Su), e = !0), \n e;\n }\n Cu(t, e) {\n // Always raise the first event when we're synced\n if (!t.fromCache) return !0;\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const n = \"Offline\" /* OnlineState.Offline */ !== e;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n return (!this.options.Nu || !n) && (!t.docs.isEmpty() || t.hasCachedResults || \"Offline\" /* OnlineState.Offline */ === e);\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n }\n Du(t) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (t.docChanges.length > 0) return !0;\n const e = this.Su && this.Su.hasPendingWrites !== t.hasPendingWrites;\n return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n }\n xu(t) {\n t = oc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults), \n this.Vu = !0, this.vu.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class wc {\n constructor(t, \n // How many bytes this element takes to store in the bundle.\n e) {\n this.ku = t, this.byteLength = e;\n }\n Ou() {\n return \"metadata\" in this.ku;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class mc {\n constructor(t) {\n this.yt = t;\n }\n Ji(t) {\n return Qs(this.yt, t);\n }\n /**\n * Converts a BundleDocument to a MutableDocument.\n */ Yi(t) {\n return t.metadata.exists ? Ys(this.yt, t.document, !1) : Ze.newNoDocument(this.Ji(t.metadata.name), this.Xi(t.metadata.readTime));\n }\n Xi(t) {\n return qs(t);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class gc {\n constructor(t, e, n) {\n this.Mu = t, this.localStore = e, this.yt = n, \n /** Batched queries to be saved into storage */\n this.queries = [], \n /** Batched documents to be saved into storage */\n this.documents = [], \n /** The collection groups affected by this bundle. */\n this.collectionGroups = new Set, this.progress = yc(t);\n }\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */ Fu(t) {\n this.progress.bytesLoaded += t.byteLength;\n let e = this.progress.documentsLoaded;\n if (t.ku.namedQuery) this.queries.push(t.ku.namedQuery); else if (t.ku.documentMetadata) {\n this.documents.push({\n metadata: t.ku.documentMetadata\n }), t.ku.documentMetadata.exists || ++e;\n const n = rt.fromString(t.ku.documentMetadata.name);\n this.collectionGroups.add(n.get(n.length - 2));\n } else t.ku.document && (this.documents[this.documents.length - 1].document = t.ku.document, \n ++e);\n return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e, \n Object.assign({}, this.progress)) : null;\n }\n $u(t) {\n const e = new Map, n = new mc(this.yt);\n for (const s of t) if (s.metadata.queries) {\n const t = n.Ji(s.metadata.name);\n for (const n of s.metadata.queries) {\n const s = (e.get(n) || Es()).add(t);\n e.set(n, s);\n }\n }\n return e;\n }\n /**\n * Update the progress to 'Success' and return the updated progress.\n */ async complete() {\n const t = await tu(this.localStore, new mc(this.yt), this.documents, this.Mu.id), e = this.$u(this.documents);\n for (const t of this.queries) await eu(this.localStore, t, e.get(t.name));\n return this.progress.taskState = \"Success\", {\n progress: this.progress,\n Bu: this.collectionGroups,\n Lu: t\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function yc(t) {\n return {\n taskState: \"Running\",\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass pc {\n constructor(t) {\n this.key = t;\n }\n}\n\nclass Ic {\n constructor(t) {\n this.key = t;\n }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class Tc {\n constructor(t, \n /** Documents included in the remote target */\n e) {\n this.query = t, this.qu = e, this.Uu = null, this.hasCachedResults = !1, \n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = !1, \n /** Documents in the view but not in the remote target */\n this.Ku = Es(), \n /** Document Keys that have local changes */\n this.mutatedKeys = Es(), this.Gu = bn(t), this.Qu = new ic(this.Gu);\n }\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */ get ju() {\n return this.qu;\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */ Wu(t, e) {\n const n = e ? e.zu : new rc, s = e ? e.Qu : this.Qu;\n let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const u = \"F\" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = \"L\" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;\n // Drop documents out to meet limit/limitToLast requirement.\n if (t.inorderTraversal(((t, e) => {\n const a = s.get(t), h = An(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations || \n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n this.mutatedKeys.has(h.key) && h.hasCommittedMutations);\n let d = !1;\n // Calculate change\n if (a && h) {\n a.data.isEqual(h.data) ? l !== f && (n.track({\n type: 3 /* ChangeType.Metadata */ ,\n doc: h\n }), d = !0) : this.Hu(a, h) || (n.track({\n type: 2 /* ChangeType.Modified */ ,\n doc: h\n }), d = !0, (u && this.Gu(h, u) > 0 || c && this.Gu(h, c) < 0) && (\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n o = !0));\n } else !a && h ? (n.track({\n type: 0 /* ChangeType.Added */ ,\n doc: h\n }), d = !0) : a && !h && (n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: a\n }), d = !0, (u || c) && (\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n o = !0));\n d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));\n })), null !== this.query.limit) for (;r.size > this.query.limit; ) {\n const t = \"F\" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();\n r = r.delete(t.key), i = i.delete(t.key), n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: t\n });\n }\n return {\n Qu: r,\n zu: n,\n $i: o,\n mutatedKeys: i\n };\n }\n Hu(t, e) {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;\n }\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param updateLimboDocuments - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(t, e, n) {\n const s = this.Qu;\n this.Qu = t.Qu, this.mutatedKeys = t.mutatedKeys;\n // Sort changes based on type and query comparator\n const i = t.zu.Eu();\n i.sort(((t, e) => function(t, e) {\n const n = t => {\n switch (t) {\n case 0 /* ChangeType.Added */ :\n return 1;\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n\n case 1 /* ChangeType.Removed */ :\n return 0;\n\n default:\n return O();\n }\n };\n return n(t) - n(e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.type, e.type) || this.Gu(t.doc, e.doc))), this.Ju(n);\n const r = e ? this.Yu() : [], o = 0 === this.Ku.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Uu;\n if (this.Uu = o, 0 !== i.length || u) {\n return {\n snapshot: new oc(this.query, t.Qu, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u, \n /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),\n Xu: r\n };\n }\n // no changes\n return {\n Xu: r\n };\n }\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */ bu(t) {\n return this.current && \"Offline\" /* OnlineState.Offline */ === t ? (\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = !1, this.applyChanges({\n Qu: this.Qu,\n zu: new rc,\n mutatedKeys: this.mutatedKeys,\n $i: !1\n }, \n /* updateLimboDocuments= */ !1)) : {\n Xu: []\n };\n }\n /**\n * Returns whether the doc for the given key should be in limbo.\n */ Zu(t) {\n // If the remote end says it's part of this query, it's not in limbo.\n return !this.qu.has(t) && (\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n !!this.Qu.has(t) && !this.Qu.get(t).hasLocalMutations);\n }\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */ Ju(t) {\n t && (t.addedDocuments.forEach((t => this.qu = this.qu.add(t))), t.modifiedDocuments.forEach((t => {})), \n t.removedDocuments.forEach((t => this.qu = this.qu.delete(t))), this.current = t.current);\n }\n Yu() {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) return [];\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const t = this.Ku;\n this.Ku = Es(), this.Qu.forEach((t => {\n this.Zu(t.key) && (this.Ku = this.Ku.add(t.key));\n }));\n // Diff the new limbo docs with the old limbo docs.\n const e = [];\n return t.forEach((t => {\n this.Ku.has(t) || e.push(new Ic(t));\n })), this.Ku.forEach((n => {\n t.has(n) || e.push(new pc(n));\n })), e;\n }\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n tc(t) {\n this.qu = t.Hi, this.Ku = Es();\n const e = this.Wu(t.documents);\n return this.applyChanges(e, /*updateLimboDocuments=*/ !0);\n }\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n ec() {\n return oc.fromInitialDocuments(this.query, this.Qu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Uu, this.hasCachedResults);\n }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass Ec {\n constructor(\n /**\n * The query itself.\n */\n t, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n e, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n n) {\n this.query = t, this.targetId = e, this.view = n;\n }\n}\n\n/** Tracks a limbo resolution. */ class Ac {\n constructor(t) {\n this.key = t, \n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n this.nc = !1;\n }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class Rc {\n constructor(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r) {\n this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s, \n this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.sc = {}, this.ic = new ls((t => Tn(t)), In), \n this.rc = new Map, \n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n this.oc = new Set, \n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n this.uc = new Ge(ct.comparator), \n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n this.cc = new Map, this.ac = new Eo, \n /** Stores user completion handlers, indexed by User and BatchId. */\n this.hc = {}, \n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n this.lc = new Map, this.fc = Yr.vn(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n this.dc = void 0;\n }\n get isPrimaryClient() {\n return !0 === this.dc;\n }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function bc(t, e) {\n const n = ta(t);\n let s, i;\n const r = n.ic.get(e);\n if (r) \n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.ec(); else {\n const t = await zo(n.localStore, gn(e));\n n.isPrimaryClient && Du(n.remoteStore, t);\n const r = n.sharedClientState.addLocalQueryTarget(t.targetId);\n s = t.targetId, i = await Pc(n, e, s, \"current\" === r, t.resumeToken);\n }\n return i;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function Pc(t, e, n, s, i) {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n t._c = (e, n, s) => async function(t, e, n, s) {\n let i = e.view.Wu(n);\n i.$i && (\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n i = await Jo(t.localStore, e.query, \n /* usePreviousResults= */ !1).then((({documents: t}) => e.view.Wu(t, i))));\n const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i, \n /* updateLimboDocuments= */ t.isPrimaryClient, r);\n return Bc(t, e.targetId, o.Xu), o.snapshot;\n }(t, e, n, s);\n const r = await Jo(t.localStore, e, \n /* usePreviousResults= */ !0), o = new Tc(e, r.Hi), u = o.Wu(r.documents), c = Ps.createSynthesizedTargetChangeForCurrentChange(n, s && \"Offline\" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u, \n /* updateLimboDocuments= */ t.isPrimaryClient, c);\n Bc(t, n, a.Xu);\n const h = new Ec(e, n, o);\n return t.ic.set(e, h), t.rc.has(n) ? t.rc.get(n).push(e) : t.rc.set(n, [ e ]), a.snapshot;\n}\n\n/** Stops listening to the query. */ async function vc(t, e) {\n const n = $(t), s = n.ic.get(e), i = n.rc.get(s.targetId);\n if (i.length > 1) return n.rc.set(s.targetId, i.filter((t => !In(t, e)))), void n.ic.delete(e);\n // No other queries are mapped to the target, clean up the query and the target.\n if (n.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n n.sharedClientState.removeLocalQueryTarget(s.targetId);\n n.sharedClientState.isActiveQueryTarget(s.targetId) || await Ho(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !1).then((() => {\n n.sharedClientState.clearQueryState(s.targetId), Cu(n.remoteStore, s.targetId), \n Fc(n, s.targetId);\n })).catch(Et);\n } else Fc(n, s.targetId), await Ho(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !0);\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function Vc(t, e, n) {\n const s = ea(t);\n try {\n const t = await function(t, e) {\n const n = $(t), s = nt.now(), i = e.reduce(((t, e) => t.add(e.key)), Es());\n let r, o;\n return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (t => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let u = ds(), c = Es();\n return n.Gi.getEntries(t, i).next((t => {\n u = t, u.forEach(((t, e) => {\n e.isValidDocument() || (c = c.add(t));\n }));\n })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {\n r = i;\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const o = [];\n for (const t of e) {\n const e = Yn(t, r.get(t.key).overlayedDocument);\n null != e && \n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n o.push(new ts(t.key, e, Xe(e.value.mapValue), Qn.exists(!0)));\n }\n return n.mutationQueue.addMutationBatch(t, s, o, e);\n })).next((e => {\n o = e;\n const s = e.applyToLocalDocumentSet(r, c);\n return n.documentOverlayCache.saveOverlays(t, e.batchId, s);\n }));\n })).then((() => ({\n batchId: o.batchId,\n changes: ms(r)\n })));\n }(s.localStore, e);\n s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {\n let s = t.hc[t.currentUser.toKey()];\n s || (s = new Ge(Z));\n s = s.insert(e, n), t.hc[t.currentUser.toKey()] = s;\n }\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (s, t.batchId, n), await Uc(s, t.changes), await Ku(s.remoteStore);\n } catch (t) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const e = sc(t, \"Failed to persist write\");\n n.reject(e);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function Sc(t, e) {\n const n = $(t);\n try {\n const t = await Qo(n.localStore, e);\n // Update `receivedDocument` as appropriate for any limbo targets.\n e.targetChanges.forEach(((t, e) => {\n const s = n.cc.get(e);\n s && (\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n M(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1), \n t.addedDocuments.size > 0 ? s.nc = !0 : t.modifiedDocuments.size > 0 ? M(s.nc) : t.removedDocuments.size > 0 && (M(s.nc), \n s.nc = !1));\n })), await Uc(n, t, e);\n } catch (t) {\n await Et(t);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function Dc(t, e, n) {\n const s = $(t);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {\n const t = [];\n s.ic.forEach(((n, s) => {\n const i = s.view.bu(e);\n i.snapshot && t.push(i.snapshot);\n })), function(t, e) {\n const n = $(t);\n n.onlineState = e;\n let s = !1;\n n.queries.forEach(((t, n) => {\n for (const t of n.listeners) \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n t.bu(e) && (s = !0);\n })), s && dc(n);\n }(s.eventManager, e), t.length && s.sc.Wo(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function Cc(t, e, n) {\n const s = $(t);\n // PORTING NOTE: Multi-tab only.\n s.sharedClientState.updateQueryState(e, \"rejected\", n);\n const i = s.cc.get(e), r = i && i.key;\n if (r) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let t = new Ge(ct.comparator);\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n t = t.insert(r, Ze.newNoDocument(r, st.min()));\n const n = Es().add(r), i = new bs(st.min(), \n /* targetChanges= */ new Map, \n /* targetMismatches= */ new We(Z), t, n);\n await Sc(s, i), \n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n s.uc = s.uc.remove(r), s.cc.delete(e), qc(s);\n } else await Ho(s.localStore, e, \n /* keepPersistedTargetData */ !1).then((() => Fc(s, e, n))).catch(Et);\n}\n\nasync function xc(t, e) {\n const n = $(t), s = e.batch.batchId;\n try {\n const t = await Ko(n.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n Mc(n, s, /*error=*/ null), Oc(n, s), n.sharedClientState.updateMutationState(s, \"acknowledged\"), \n await Uc(n, t);\n } catch (t) {\n await Et(t);\n }\n}\n\nasync function Nc(t, e, n) {\n const s = $(t);\n try {\n const t = await function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (t => {\n let s;\n return n.mutationQueue.lookupMutationBatch(t, e).next((e => (M(null !== e), s = e.keys(), \n n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));\n }));\n }\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (s.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n Mc(s, e, n), Oc(s, e), s.sharedClientState.updateMutationState(e, \"rejected\", n), \n await Uc(s, t);\n } catch (n) {\n await Et(n);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function kc(t, e) {\n const n = $(t);\n Mu(n.remoteStore) || C(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n try {\n const t = await function(t) {\n const e = $(t);\n return e.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));\n }(n.localStore);\n if (-1 === t) \n // Trigger the callback right away if there is no pending writes at the moment.\n return void e.resolve();\n const s = n.lc.get(t) || [];\n s.push(e), n.lc.set(t, s);\n } catch (t) {\n const n = sc(t, \"Initialization of waitForPendingWrites() operation failed\");\n e.reject(n);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function Oc(t, e) {\n (t.lc.get(e) || []).forEach((t => {\n t.resolve();\n })), t.lc.delete(e);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function Mc(t, e, n) {\n const s = $(t);\n let i = s.hc[s.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (i) {\n const t = i.get(e);\n t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.hc[s.currentUser.toKey()] = i;\n }\n}\n\nfunction Fc(t, e, n = null) {\n t.sharedClientState.removeLocalQueryTarget(e);\n for (const s of t.rc.get(e)) t.ic.delete(s), n && t.sc.wc(s, n);\n if (t.rc.delete(e), t.isPrimaryClient) {\n t.ac.ls(e).forEach((e => {\n t.ac.containsKey(e) || \n // We removed the last reference for this key\n $c(t, e);\n }));\n }\n}\n\nfunction $c(t, e) {\n t.oc.delete(e.path.canonicalString());\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const n = t.uc.get(e);\n null !== n && (Cu(t.remoteStore, n), t.uc = t.uc.remove(e), t.cc.delete(n), qc(t));\n}\n\nfunction Bc(t, e, n) {\n for (const s of n) if (s instanceof pc) t.ac.addReference(s.key, e), Lc(t, s); else if (s instanceof Ic) {\n C(\"SyncEngine\", \"Document no longer in limbo: \" + s.key), t.ac.removeReference(s.key, e);\n t.ac.containsKey(s.key) || \n // We removed the last reference for this key\n $c(t, s.key);\n } else O();\n}\n\nfunction Lc(t, e) {\n const n = e.key, s = n.path.canonicalString();\n t.uc.get(n) || t.oc.has(s) || (C(\"SyncEngine\", \"New document in limbo: \" + n), t.oc.add(s), \n qc(t));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function qc(t) {\n for (;t.oc.size > 0 && t.uc.size < t.maxConcurrentLimboResolutions; ) {\n const e = t.oc.values().next().value;\n t.oc.delete(e);\n const n = new ct(rt.fromString(e)), s = t.fc.next();\n t.cc.set(s, new Ac(n)), t.uc = t.uc.insert(n, s), Du(t.remoteStore, new zi(gn(ln(n.path)), s, 2 /* TargetPurpose.LimboResolution */ , Ot.at));\n }\n}\n\nasync function Uc(t, e, n) {\n const s = $(t), i = [], r = [], o = [];\n s.ic.isEmpty() || (s.ic.forEach(((t, u) => {\n o.push(s._c(u, e, n).then((t => {\n // Update views if there are actual changes.\n if (\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? \"not-current\" : \"current\"), \n t) {\n i.push(t);\n const e = $o.Ci(u.targetId, t);\n r.push(e);\n }\n })));\n })), await Promise.all(o), s.sc.Wo(i), await async function(t, e) {\n const n = $(t);\n try {\n await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (t => At.forEach(e, (e => At.forEach(e.Si, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => At.forEach(e.Di, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));\n } catch (t) {\n if (!Vt(t)) throw t;\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n C(\"LocalStore\", \"Failed to update sequence numbers: \" + t);\n }\n for (const t of e) {\n const e = t.targetId;\n if (!t.fromCache) {\n const t = n.qi.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);\n // Advance the last limbo free snapshot version\n n.qi = n.qi.insert(e, i);\n }\n }\n }(s.localStore, r));\n}\n\nasync function Kc(t, e) {\n const n = $(t);\n if (!n.currentUser.isEqual(e)) {\n C(\"SyncEngine\", \"User change. New user:\", e.toKey());\n const t = await Uo(n.localStore, e);\n n.currentUser = e, \n // Fails tasks waiting for pending writes requested by previous user.\n function(t, e) {\n t.lc.forEach((t => {\n t.forEach((t => {\n t.reject(new L(B.CANCELLED, e));\n }));\n })), t.lc.clear();\n }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n // TODO(b/114226417): Consider calling this only in the primary tab.\n n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await Uc(n, t.ji);\n }\n}\n\nfunction Gc(t, e) {\n const n = $(t), s = n.cc.get(e);\n if (s && s.nc) return Es().add(s.key);\n {\n let t = Es();\n const s = n.rc.get(e);\n if (!s) return t;\n for (const e of s) {\n const s = n.ic.get(e);\n t = t.unionWith(s.view.ju);\n }\n return t;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function Qc(t, e) {\n const n = $(t), s = await Jo(n.localStore, e.query, \n /* usePreviousResults= */ !0), i = e.view.tc(s);\n return n.isPrimaryClient && Bc(n, e.targetId, i.Xu), i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function jc(t, e) {\n const n = $(t);\n return Xo(n.localStore, e).then((t => Uc(n, t)));\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nasync function Wc(t, e, n, s) {\n const i = $(t), r = await function(t, e) {\n const n = $(t), s = $(n.mutationQueue);\n return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (t => s.Tn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : At.resolve(null)))));\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e);\n null !== r ? (\"pending\" === n ? \n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await Ku(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n Mc(i, e, s || null), Oc(i, e), function(t, e) {\n $($(t).mutationQueue).An(e);\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e)) : O(), await Uc(i, r)) : \n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n C(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + e);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function zc(t, e) {\n const n = $(t);\n if (ta(n), ea(n), !0 === e && !0 !== n.dc) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const t = n.sharedClientState.getAllActiveQueryTargets(), e = await Hc(n, t.toArray());\n n.dc = !0, await Zu(n.remoteStore, !0);\n for (const t of e) Du(n.remoteStore, t);\n } else if (!1 === e && !1 !== n.dc) {\n const t = [];\n let e = Promise.resolve();\n n.rc.forEach(((s, i) => {\n n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (Fc(n, i), \n Ho(n.localStore, i, \n /*keepPersistedTargetData=*/ !0)))), Cu(n.remoteStore, i);\n })), await e, await Hc(n, t), \n // PORTING NOTE: Multi-Tab only.\n function(t) {\n const e = $(t);\n e.cc.forEach(((t, n) => {\n Cu(e.remoteStore, n);\n })), e.ac.fs(), e.cc = new Map, e.uc = new Ge(ct.comparator);\n }\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n // PORTING NOTE: Multi-Tab only.\n (n), n.dc = !1, await Zu(n.remoteStore, !1);\n }\n}\n\nasync function Hc(t, e, n) {\n const s = $(t), i = [], r = [];\n for (const t of e) {\n let e;\n const n = s.rc.get(t);\n if (n && 0 !== n.length) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n e = await zo(s.localStore, gn(n[0]));\n for (const t of n) {\n const e = s.ic.get(t), n = await Qc(s, e);\n n.snapshot && r.push(n.snapshot);\n }\n } else {\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const n = await Yo(s.localStore, t);\n e = await zo(s.localStore, n), await Pc(s, Jc(n), t, \n /*current=*/ !1, e.resumeToken);\n }\n i.push(e);\n }\n return s.sc.Wo(r), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction Jc(t) {\n return hn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, \"F\" /* LimitType.First */ , t.startAt, t.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction Yc(t) {\n const e = $(t);\n return $($(e.localStore).persistence).vi();\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function Xc(t, e, n, s) {\n const i = $(t);\n if (i.dc) \n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n return void C(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n const r = i.rc.get(e);\n if (r && r.length > 0) switch (n) {\n case \"current\":\n case \"not-current\":\n {\n const t = await Xo(i.localStore, Rn(r[0])), s = bs.createSynthesizedRemoteEventForCurrentChange(e, \"current\" === n, Qt.EMPTY_BYTE_STRING);\n await Uc(i, t, s);\n break;\n }\n\n case \"rejected\":\n await Ho(i.localStore, e, \n /* keepPersistedTargetData */ !0), Fc(i, e, s);\n break;\n\n default:\n O();\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function Zc(t, e, n) {\n const s = ta(t);\n if (s.dc) {\n for (const t of e) {\n if (s.rc.has(t)) {\n // A target might have been added in a previous attempt\n C(\"SyncEngine\", \"Adding an already active target \" + t);\n continue;\n }\n const e = await Yo(s.localStore, t), n = await zo(s.localStore, e);\n await Pc(s, Jc(e), n.targetId, \n /*current=*/ !1, n.resumeToken), Du(s.remoteStore, n);\n }\n for (const t of n) \n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n s.rc.has(t) && \n // Release queries that are still active.\n await Ho(s.localStore, t, \n /* keepPersistedTargetData */ !1).then((() => {\n Cu(s.remoteStore, t), Fc(s, t);\n })).catch(Et);\n }\n}\n\nfunction ta(t) {\n const e = $(t);\n return e.remoteStore.remoteSyncer.applyRemoteEvent = Sc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = Gc.bind(null, e), \n e.remoteStore.remoteSyncer.rejectListen = Cc.bind(null, e), e.sc.Wo = lc.bind(null, e.eventManager), \n e.sc.wc = fc.bind(null, e.eventManager), e;\n}\n\nfunction ea(t) {\n const e = $(t);\n return e.remoteStore.remoteSyncer.applySuccessfulWrite = xc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Nc.bind(null, e), \n e;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function na(t, e, n) {\n const s = $(t);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (\n /** Loads a bundle and returns the list of affected collection groups. */\n async function(t, e, n) {\n try {\n const s = await e.getMetadata();\n if (await function(t, e) {\n const n = $(t), s = qs(e.createTime);\n return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (t => n.Ns.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));\n }\n /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {\n return {\n taskState: \"Success\",\n documentsLoaded: t.totalDocuments,\n bytesLoaded: t.totalBytes,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n }(s)), Promise.resolve(new Set);\n n._updateProgress(yc(s));\n const i = new gc(s, t.localStore, e.yt);\n let r = await e.mc();\n for (;r; ) {\n const t = await i.Fu(r);\n t && n._updateProgress(t), r = await e.mc();\n }\n const o = await i.complete();\n return await Uc(t, o.Lu, \n /* remoteEvent */ void 0), \n // Save metadata, so loading the same bundle will skip.\n await function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (t => n.Ns.saveBundleMetadata(t, e)));\n }\n /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Bu);\n } catch (t) {\n return N(\"SyncEngine\", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(s, e, n).then((t => {\n s.sharedClientState.notifyBundleLoaded(t);\n }));\n}\n\nclass sa {\n constructor() {\n this.synchronizeTabs = !1;\n }\n async initialize(t) {\n this.yt = pu(t.databaseInfo.databaseId), this.sharedClientState = this.gc(t), this.persistence = this.yc(t), \n await this.persistence.start(), this.localStore = this.Ic(t), this.gcScheduler = this.Tc(t, this.localStore), \n this.indexBackfillerScheduler = this.Ec(t, this.localStore);\n }\n Tc(t, e) {\n return null;\n }\n Ec(t, e) {\n return null;\n }\n Ic(t) {\n return qo(this.persistence, new Bo, t.initialUser, this.yt);\n }\n yc(t) {\n return new Vo(Do.Bs, this.yt);\n }\n gc(t) {\n return new lu;\n }\n async terminate() {\n this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(), \n await this.persistence.shutdown();\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class ia extends sa {\n constructor(t, e, n) {\n super(), this.Ac = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;\n }\n async initialize(t) {\n await super.initialize(t), await this.Ac.initialize(this, t), \n // Enqueue writes from a previous session\n await ea(this.Ac.syncEngine), await Ku(this.Ac.remoteStore), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.li((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), \n this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), \n Promise.resolve())));\n }\n Ic(t) {\n return qo(this.persistence, new Bo, t.initialUser, this.yt);\n }\n Tc(t, e) {\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new io(n, t.asyncQueue, e);\n }\n Ec(t, e) {\n const n = new kt(e, this.persistence);\n return new Nt(t.asyncQueue, n);\n }\n yc(t) {\n const e = Fo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? Kr.withCacheSize(this.cacheSizeBytes) : Kr.DEFAULT;\n return new ko(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, gu(), yu(), this.yt, this.sharedClientState, !!this.forceOwnership);\n }\n gc(t) {\n return new lu;\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class ra extends ia {\n constructor(t, e) {\n super(t, e, /* forceOwnership= */ !1), this.Ac = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;\n }\n async initialize(t) {\n await super.initialize(t);\n const e = this.Ac.syncEngine;\n this.sharedClientState instanceof hu && (this.sharedClientState.syncEngine = {\n Fr: Wc.bind(null, e),\n $r: Xc.bind(null, e),\n Br: Zc.bind(null, e),\n vi: Yc.bind(null, e),\n Mr: jc.bind(null, e)\n }, await this.sharedClientState.start()), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.li((async t => {\n await zc(this.Ac.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()), \n this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());\n }));\n }\n gc(t) {\n const e = gu();\n if (!hu.C(e)) throw new L(B.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n const n = Fo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);\n return new hu(e, t.asyncQueue, n, t.clientId, t.initialUser);\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class oa {\n async initialize(t, e) {\n this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState, \n this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e), \n this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e, \n /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Dc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */), \n this.remoteStore.remoteSyncer.handleCredentialChange = Kc.bind(null, this.syncEngine), \n await Zu(this.remoteStore, this.syncEngine.isPrimaryClient));\n }\n createEventManager(t) {\n return new cc;\n }\n createDatastore(t) {\n const e = pu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new mu(s));\n var s;\n /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {\n return new Ru(t, e, n, s);\n }(t.authCredentials, t.appCheckCredentials, n, e);\n }\n createRemoteStore(t) {\n return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Dc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */), \n r = du.C() ? new du : new fu, new vu(e, n, s, i, r);\n var e, n, s, i, r;\n /** Re-enables the network. Idempotent. */ }\n createSyncEngine(t, e) {\n return function(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r, o) {\n const u = new Rc(t, e, n, s, i, r);\n return o && (u.dc = !0), u;\n }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);\n }\n terminate() {\n return async function(t) {\n const e = $(t);\n C(\"RemoteStore\", \"RemoteStore shutting down.\"), e._u.add(5 /* OfflineCause.Shutdown */), \n await Su(e), e.mu.shutdown(), \n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n e.gu.set(\"Unknown\" /* OnlineState.Unknown */);\n }(this.remoteStore);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function ua(t, e, n) {\n if (!n) throw new L(B.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function ca(t, e, n, s) {\n if (!0 === e && !0 === s) throw new L(B.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function aa(t) {\n if (!ct.isDocumentKey(t)) throw new L(B.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function ha(t) {\n if (ct.isDocumentKey(t)) throw new L(B.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction la(t) {\n if (void 0 === t) return \"undefined\";\n if (null === t) return \"null\";\n if (\"string\" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), \n JSON.stringify(t);\n if (\"number\" == typeof t || \"boolean\" == typeof t) return \"\" + t;\n if (\"object\" == typeof t) {\n if (t instanceof Array) return \"an array\";\n {\n const e = \n /** try to get the constructor name for an object. */\n function(t) {\n if (t.constructor) return t.constructor.name;\n return null;\n }\n /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (t);\n return e ? `a custom ${e} object` : \"an object\";\n }\n }\n return \"function\" == typeof t ? \"a function\" : O();\n}\n\nfunction fa(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n if (\"_delegate\" in t && (\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t = t._delegate), !(t instanceof e)) {\n if (e.name === t.constructor.name) throw new L(B.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n {\n const n = la(t);\n throw new L(B.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);\n }\n }\n return t;\n}\n\nfunction da(t, e) {\n if (e <= 0) throw new L(B.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const _a = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass wa {\n constructor(t) {\n var e;\n if (void 0 === t.host) {\n if (void 0 !== t.ssl) throw new L(B.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n this.host = \"firestore.googleapis.com\", this.ssl = true;\n } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;\n if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, \n void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new L(B.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n this.cacheSizeBytes = t.cacheSizeBytes;\n }\n this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, \n this.useFetchStreams = !!t.useFetchStreams, ca(\"experimentalForceLongPolling\", t.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", t.experimentalAutoDetectLongPolling);\n }\n isEqual(t) {\n return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ class ma {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n, \n this._app = s, \n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new wa({}), \n this._settingsFrozen = !1;\n }\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */ get app() {\n if (!this._app) throw new L(B.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n return this._app;\n }\n get _initialized() {\n return this._settingsFrozen;\n }\n get _terminated() {\n return void 0 !== this._terminateTask;\n }\n _setSettings(t) {\n if (this._settingsFrozen) throw new L(B.FAILED_PRECONDITION, \"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.\");\n this._settings = new wa(t), void 0 !== t.credentials && (this._authCredentials = function(t) {\n if (!t) return new K;\n switch (t.type) {\n case \"gapi\":\n const e = t.client;\n return new W(e, t.sessionIndex || \"0\", t.iamToken || null, t.authTokenFactory || null);\n\n case \"provider\":\n return t.client;\n\n default:\n throw new L(B.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n }\n }(t.credentials));\n }\n _getSettings() {\n return this._settings;\n }\n _freezeSettings() {\n return this._settingsFrozen = !0, this._settings;\n }\n _delete() {\n return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;\n }\n /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */ _terminate() {\n /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n return function(t) {\n const e = _a.get(t);\n e && (C(\"ComponentProvider\", \"Removing Datastore\"), _a.delete(t), e.terminate());\n }(this), Promise.resolve();\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ function ga(t, e, n, s = {}) {\n var i;\n const r = (t = fa(t, ma))._getSettings();\n if (\"firestore.googleapis.com\" !== r.host && r.host !== e && N(\"Host has been set in both settings() and useEmulator(), emulator host will be used\"), \n t._setSettings(Object.assign(Object.assign({}, r), {\n host: `${e}:${n}`,\n ssl: !1\n })), s.mockUserToken) {\n let e, n;\n if (\"string\" == typeof s.mockUserToken) e = s.mockUserToken, n = P.MOCK_USER; else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n e = f(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);\n const r = s.mockUserToken.sub || s.mockUserToken.user_id;\n if (!r) throw new L(B.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n n = new P(r);\n }\n t._authCredentials = new G(new U(e, n));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class ya {\n /** @hideconstructor */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._key = n, \n /** The type of this Firestore reference. */\n this.type = \"document\", this.firestore = t;\n }\n get _path() {\n return this._key.path;\n }\n /**\n * The document's identifier within its collection.\n */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */ get path() {\n return this._key.path.canonicalString();\n }\n /**\n * The collection this `DocumentReference` belongs to.\n */ get parent() {\n return new Ia(this.firestore, this.converter, this._key.path.popLast());\n }\n withConverter(t) {\n return new ya(this.firestore, t, this._key);\n }\n}\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class pa {\n // This is the lite version of the Query class in the main SDK.\n /** @hideconstructor protected */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._query = n, \n /** The type of this Firestore reference. */\n this.type = \"query\", this.firestore = t;\n }\n withConverter(t) {\n return new pa(this.firestore, t, this._query);\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link query}).\n */ class Ia extends pa {\n /** @hideconstructor */\n constructor(t, e, n) {\n super(t, e, ln(n)), this._path = n, \n /** The type of this Firestore reference. */\n this.type = \"collection\";\n }\n /** The collection's identifier. */ get id() {\n return this._query.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */ get path() {\n return this._query.path.canonicalString();\n }\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */ get parent() {\n const t = this._path.popLast();\n return t.isEmpty() ? null : new ya(this.firestore, \n /* converter= */ null, new ct(t));\n }\n withConverter(t) {\n return new Ia(this.firestore, t, this._path);\n }\n}\n\nfunction Ta(t, e, ...n) {\n if (t = d(t), ua(\"collection\", \"path\", e), t instanceof ma) {\n const s = rt.fromString(e, ...n);\n return ha(s), new Ia(t, /* converter= */ null, s);\n }\n {\n if (!(t instanceof ya || t instanceof Ia)) throw new L(B.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(rt.fromString(e, ...n));\n return ha(s), new Ia(t.firestore, \n /* converter= */ null, s);\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function Ea(t, e) {\n if (t = fa(t, ma), ua(\"collectionGroup\", \"collection id\", e), e.indexOf(\"/\") >= 0) throw new L(B.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n return new pa(t, \n /* converter= */ null, function(t) {\n return new an(rt.emptyPath(), t);\n }(e));\n}\n\nfunction Aa(t, e, ...n) {\n if (t = d(t), \n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n 1 === arguments.length && (e = X.R()), ua(\"doc\", \"path\", e), t instanceof ma) {\n const s = rt.fromString(e, ...n);\n return aa(s), new ya(t, \n /* converter= */ null, new ct(s));\n }\n {\n if (!(t instanceof ya || t instanceof Ia)) throw new L(B.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(rt.fromString(e, ...n));\n return aa(s), new ya(t.firestore, t instanceof Ia ? t.converter : null, new ct(s));\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function Ra(t, e) {\n return t = d(t), e = d(e), (t instanceof ya || t instanceof Ia) && (e instanceof ya || e instanceof Ia) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function ba(t, e) {\n return t = d(t), e = d(e), t instanceof pa && e instanceof pa && (t.firestore === e.firestore && In(t._query, e._query) && t.converter === e.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nfunction Pa(t, e = 10240) {\n let n = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read() {\n if (n < t.byteLength) {\n const s = {\n value: t.slice(n, n + e),\n done: !1\n };\n return n += e, s;\n }\n return {\n done: !0\n };\n },\n async cancel() {},\n releaseLock() {},\n closed: Promise.reject(\"unimplemented\")\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass va {\n constructor(t) {\n this.observer = t, \n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = !1;\n }\n next(t) {\n this.observer.next && this.Rc(this.observer.next, t);\n }\n error(t) {\n this.observer.error ? this.Rc(this.observer.error, t) : x(\"Uncaught Error in snapshot listener:\", t.toString());\n }\n bc() {\n this.muted = !0;\n }\n Rc(t, e) {\n this.muted || setTimeout((() => {\n this.muted || t(e);\n }), 0);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class Va {\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n t, e) {\n this.Pc = t, this.yt = e, \n /** Cached bundle metadata. */\n this.metadata = new q, \n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n this.buffer = new Uint8Array, this.vc = new TextDecoder(\"utf-8\"), \n // Read the metadata (which is the first element).\n this.Vc().then((t => {\n t && t.Ou() ? this.metadata.resolve(t.ku.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n ${JSON.stringify(null == t ? void 0 : t.ku)}`));\n }), (t => this.metadata.reject(t)));\n }\n close() {\n return this.Pc.cancel();\n }\n async getMetadata() {\n return this.metadata.promise;\n }\n async mc() {\n // Makes sure metadata is read before proceeding.\n return await this.getMetadata(), this.Vc();\n }\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */ async Vc() {\n const t = await this.Sc();\n if (null === t) return null;\n const e = this.vc.decode(t), n = Number(e);\n isNaN(n) && this.Dc(`length string (${e}) is not valid number`);\n const s = await this.Cc(n);\n return new wc(JSON.parse(s), t.length + n);\n }\n /** First index of '{' from the underlying buffer. */ xc() {\n return this.buffer.findIndex((t => t === \"{\".charCodeAt(0)));\n }\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */ async Sc() {\n for (;this.xc() < 0; ) {\n if (await this.Nc()) break;\n }\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (0 === this.buffer.length) return null;\n const t = this.xc();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n t < 0 && this.Dc(\"Reached the end of bundle when a length string is expected.\");\n const e = this.buffer.slice(0, t);\n // Update the internal buffer to drop the read length.\n return this.buffer = this.buffer.slice(t), e;\n }\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */ async Cc(t) {\n for (;this.buffer.length < t; ) {\n await this.Nc() && this.Dc(\"Reached the end of bundle when more is expected.\");\n }\n const e = this.vc.decode(this.buffer.slice(0, t));\n // Update the internal buffer to drop the read json string.\n return this.buffer = this.buffer.slice(t), e;\n }\n Dc(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n throw this.Pc.cancel(), new Error(`Invalid bundle format: ${t}`);\n }\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */ async Nc() {\n const t = await this.Pc.read();\n if (!t.done) {\n const e = new Uint8Array(this.buffer.length + t.value.length);\n e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;\n }\n return t.done;\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass Sa {\n constructor() {\n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateField\";\n }\n}\n\n/**\n * The results of executing an aggregation query.\n */ class Da {\n /** @hideconstructor */\n constructor(t, e) {\n this._data = e, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateQuerySnapshot\", this.query = t;\n }\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */ data() {\n return this._data;\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * CountQueryRunner encapsulates the logic needed to run the count aggregation\n * queries.\n */ class Ca {\n constructor(t, e, n) {\n this.query = t, this.datastore = e, this.userDataWriter = n;\n }\n run() {\n return bu(this.datastore, this.query._query).then((t => {\n M(void 0 !== t[0]);\n const e = Object.entries(t[0]).filter((([t, e]) => \"count_alias\" === t)).map((([t, e]) => this.userDataWriter.convertValue(e)))[0];\n return M(\"number\" == typeof e), Promise.resolve(new Da(this.query, {\n count: e\n }));\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */ class xa {\n constructor(t) {\n this.datastore = t, \n // The version of each document that was read during this transaction.\n this.readVersions = new Map, this.mutations = [], this.committed = !1, \n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n this.lastWriteError = null, \n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n this.writtenDocs = new Set;\n }\n async lookup(t) {\n if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new L(B.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\");\n const e = await async function(t, e) {\n const n = $(t), s = zs(n.yt) + \"/documents\", i = {\n documents: e.map((t => Gs(n.yt, t)))\n }, r = await n._o(\"BatchGetDocuments\", s, i, e.length), o = new Map;\n r.forEach((t => {\n const e = Xs(n.yt, t);\n o.set(e.key.toString(), e);\n }));\n const u = [];\n return e.forEach((t => {\n const e = o.get(t.toString());\n M(!!e), u.push(e);\n })), u;\n }(this.datastore, t);\n return e.forEach((t => this.recordVersion(t))), e;\n }\n set(t, e) {\n this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n update(t, e) {\n try {\n this.write(e.toMutation(t, this.preconditionForUpdate(t)));\n } catch (t) {\n this.lastWriteError = t;\n }\n this.writtenDocs.add(t.toString());\n }\n delete(t) {\n this.write(new is(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n async commit() {\n if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;\n const t = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach((e => {\n t.delete(e.key.toString());\n })), \n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n t.forEach(((t, e) => {\n const n = ct.fromPath(e);\n this.mutations.push(new rs(n, this.precondition(n)));\n })), await async function(t, e) {\n const n = $(t), s = zs(n.yt) + \"/documents\", i = {\n writes: e.map((t => ti(n.yt, t)))\n };\n await n.ao(\"Commit\", s, i);\n }(this.datastore, this.mutations), this.committed = !0;\n }\n recordVersion(t) {\n let e;\n if (t.isFoundDocument()) e = t.version; else {\n if (!t.isNoDocument()) throw O();\n // Represent a deleted doc using SnapshotVersion.min().\n e = st.min();\n }\n const n = this.readVersions.get(t.key.toString());\n if (n) {\n if (!e.isEqual(n)) \n // This transaction will fail no matter what.\n throw new L(B.ABORTED, \"Document version changed between two reads.\");\n } else this.readVersions.set(t.key.toString(), e);\n }\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */ precondition(t) {\n const e = this.readVersions.get(t.toString());\n return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(st.min()) ? Qn.exists(!1) : Qn.updateTime(e) : Qn.none();\n }\n /**\n * Returns the precondition for a document if the operation is an update.\n */ preconditionForUpdate(t) {\n const e = this.readVersions.get(t.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(t.toString()) && e) {\n if (e.isEqual(st.min())) \n // The document doesn't exist, so fail the transaction.\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new L(B.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n // Document exists, base precondition on document update time.\n return Qn.updateTime(e);\n }\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Qn.exists(!0);\n }\n write(t) {\n this.ensureCommitNotCalled(), this.mutations.push(t);\n }\n ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */ class Na {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s, \n this.deferred = i, this.kc = n.maxAttempts, this.xo = new Iu(this.asyncQueue, \"transaction_retry\" /* TimerId.TransactionRetry */);\n }\n /** Runs the transaction and sets the result on deferred. */ run() {\n this.kc -= 1, this.Oc();\n }\n Oc() {\n this.xo.Ro((async () => {\n const t = new xa(this.datastore), e = this.Mc(t);\n e && e.then((e => {\n this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {\n this.deferred.resolve(e);\n })).catch((t => {\n this.Fc(t);\n }))));\n })).catch((t => {\n this.Fc(t);\n }));\n }));\n }\n Mc(t) {\n try {\n const e = this.updateFunction(t);\n return !qt(e) && e.catch && e.then ? e : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n null);\n } catch (t) {\n // Do not retry errors thrown by user provided updateFunction.\n return this.deferred.reject(t), null;\n }\n }\n Fc(t) {\n this.kc > 0 && this.$c(t) ? (this.kc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Oc(), \n Promise.resolve())))) : this.deferred.reject(t);\n }\n $c(t) {\n if (\"FirebaseError\" === t.name) {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const e = t.code;\n return \"aborted\" === e || \"failed-precondition\" === e || \"already-exists\" === e || !as(e);\n }\n return !1;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the\n * pieces of the client SDK architecture. It is responsible for creating the\n * async queue that is shared by all of the other components in the system.\n */\nclass ka {\n constructor(t, e, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n n, s) {\n this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s, \n this.user = P.UNAUTHENTICATED, this.clientId = X.R(), this.authCredentialListener = () => Promise.resolve(), \n this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {\n C(\"FirestoreClient\", \"Received user=\", t.uid), await this.authCredentialListener(t), \n this.user = t;\n })), this.appCheckCredentials.start(n, (t => (C(\"FirestoreClient\", \"Received new app check token=\", t), \n this.appCheckCredentialListener(t, this.user))));\n }\n async getConfiguration() {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: 100\n };\n }\n setCredentialChangeListener(t) {\n this.authCredentialListener = t;\n }\n setAppCheckTokenChangeListener(t) {\n this.appCheckCredentialListener = t;\n }\n /**\n * Checks that the client has not been terminated. Ensures that other methods on\n * this class cannot be called after the client is terminated.\n */ verifyNotTerminated() {\n if (this.asyncQueue.isShuttingDown) throw new L(B.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n terminate() {\n this.asyncQueue.enterRestrictedMode();\n const t = new q;\n return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n this.onlineComponents && await this.onlineComponents.terminate(), this.offlineComponents && await this.offlineComponents.terminate(), \n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();\n } catch (e) {\n const n = sc(e, \"Failed to shutdown persistence\");\n t.reject(n);\n }\n })), t.promise;\n }\n}\n\nasync function Oa(t, e) {\n t.asyncQueue.verifyOperationInProgress(), C(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n const n = await t.getConfiguration();\n await e.initialize(n);\n let s = n.initialUser;\n t.setCredentialChangeListener((async t => {\n s.isEqual(t) || (await Uo(e.localStore, t), s = t);\n })), \n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n e.persistence.setDatabaseDeletedListener((() => t.terminate())), t.offlineComponents = e;\n}\n\nasync function Ma(t, e) {\n t.asyncQueue.verifyOperationInProgress();\n const n = await Fa(t);\n C(\"FirestoreClient\", \"Initializing OnlineComponentProvider\");\n const s = await t.getConfiguration();\n await e.initialize(n, s), \n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n t.setCredentialChangeListener((t => Xu(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => Xu(e.remoteStore, n))), \n t.onlineComponents = e;\n}\n\nasync function Fa(t) {\n return t.offlineComponents || (C(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), \n await Oa(t, new sa)), t.offlineComponents;\n}\n\nasync function $a(t) {\n return t.onlineComponents || (C(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n await Ma(t, new oa)), t.onlineComponents;\n}\n\nfunction Ba(t) {\n return Fa(t).then((t => t.persistence));\n}\n\nfunction La(t) {\n return Fa(t).then((t => t.localStore));\n}\n\nfunction qa(t) {\n return $a(t).then((t => t.remoteStore));\n}\n\nfunction Ua(t) {\n return $a(t).then((t => t.syncEngine));\n}\n\nfunction Ka(t) {\n return $a(t).then((t => t.datastore));\n}\n\nasync function Ga(t) {\n const e = await $a(t), n = e.eventManager;\n return n.onListen = bc.bind(null, e.syncEngine), n.onUnlisten = vc.bind(null, e.syncEngine), \n n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function Qa(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Ba(t), n = await qa(t);\n return e.setNetworkEnabled(!0), function(t) {\n const e = $(t);\n return e._u.delete(0 /* OfflineCause.UserDisabled */), Vu(e);\n }(n);\n }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function ja(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Ba(t), n = await qa(t);\n return e.setNetworkEnabled(!1), async function(t) {\n const e = $(t);\n e._u.add(0 /* OfflineCause.UserDisabled */), await Su(e), \n // Set the OnlineState to Offline so get()s return from cache, etc.\n e.gu.set(\"Offline\" /* OnlineState.Offline */);\n }(n);\n }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function Wa(t, e) {\n const n = new q;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"read document\", \"readonly\", (t => n.localDocuments.getDocument(t, e)));\n }(t, e);\n s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new L(B.UNAVAILABLE, \"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\"));\n } catch (t) {\n const s = sc(t, `Failed to get document '${e} from cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await La(t), e, n))), n.promise;\n}\n\nfunction za(t, e, n = {}) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new va({\n next: r => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => hc(t, o)));\n const u = r.docs.has(n);\n !u && r.fromCache ? \n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n i.reject(new L(B.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : u && r.fromCache && s && \"server\" === s.source ? i.reject(new L(B.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')) : i.resolve(r);\n },\n error: t => i.reject(t)\n }), o = new _c(ln(n.path), r, {\n includeMetadataChanges: !0,\n Nu: !0\n });\n return ac(t, o);\n }(await Ga(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Ha(t, e) {\n const n = new q;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await Jo(t, e, \n /* usePreviousResults= */ !0), i = new Tc(e, s.Hi), r = i.Wu(s.documents), o = i.applyChanges(r, \n /* updateLimboDocuments= */ !1);\n n.resolve(o.snapshot);\n } catch (t) {\n const s = sc(t, `Failed to execute query '${e} against cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await La(t), e, n))), n.promise;\n}\n\nfunction Ja(t, e, n = {}) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new va({\n next: n => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => hc(t, o))), n.fromCache && \"server\" === s.source ? i.reject(new L(B.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')) : i.resolve(n);\n },\n error: t => i.reject(t)\n }), o = new _c(n, r, {\n includeMetadataChanges: !0,\n Nu: !0\n });\n return ac(t, o);\n }(await Ga(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Ya(t, e) {\n const n = new va(e);\n return t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n $(t).Ru.add(e), \n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n e.next();\n }(await Ga(t), n))), () => {\n n.bc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n $(t).Ru.delete(e);\n }(await Ga(t), n)));\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function Xa(t, e, n, s) {\n const i = function(t, e) {\n let n;\n n = \"string\" == typeof t ? (new TextEncoder).encode(t) : t;\n return function(t, e) {\n return new Va(t, e);\n }(function(t, e) {\n if (t instanceof Uint8Array) return Pa(t, e);\n if (t instanceof ArrayBuffer) return Pa(new Uint8Array(t), e);\n if (t instanceof ReadableStream) return t.getReader();\n throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n }(n), e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n, pu(e));\n t.asyncQueue.enqueueAndForget((async () => {\n na(await Ua(t), i, s);\n }));\n}\n\nfunction Za(t, e) {\n return t.asyncQueue.enqueue((async () => function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Get named query\", \"readonly\", (t => n.Ns.getNamedQuery(t, e)));\n }(await La(t), e)));\n}\n\nclass th {\n constructor() {\n // The last promise in the queue.\n this.Bc = Promise.resolve(), \n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n this.Lc = [], \n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n this.qc = !1, \n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.Uc = [], \n // visible for testing\n this.Kc = null, \n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.Gc = !1, \n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n this.Qc = !1, \n // List of TimerIds to fast-forward delays for.\n this.jc = [], \n // Backoff timer used to schedule retries for retryable operations\n this.xo = new Iu(this, \"async_queue_retry\" /* TimerId.AsyncQueueRetry */), \n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n this.Wc = () => {\n const t = yu();\n t && C(\"AsyncQueue\", \"Visibility state changed to \" + t.visibilityState), this.xo.Po();\n };\n const t = yu();\n t && \"function\" == typeof t.addEventListener && t.addEventListener(\"visibilitychange\", this.Wc);\n }\n get isShuttingDown() {\n return this.qc;\n }\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */ enqueueAndForget(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(t);\n }\n enqueueAndForgetEvenWhileRestricted(t) {\n this.zc(), \n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.Hc(t);\n }\n enterRestrictedMode(t) {\n if (!this.qc) {\n this.qc = !0, this.Qc = t || !1;\n const e = yu();\n e && \"function\" == typeof e.removeEventListener && e.removeEventListener(\"visibilitychange\", this.Wc);\n }\n }\n enqueue(t) {\n if (this.zc(), this.qc) \n // Return a Promise which never resolves.\n return new Promise((() => {}));\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const e = new q;\n return this.Hc((() => this.qc && this.Qc ? Promise.resolve() : (t().then(e.resolve, e.reject), \n e.promise))).then((() => e.promise));\n }\n enqueueRetryable(t) {\n this.enqueueAndForget((() => (this.Lc.push(t), this.Jc())));\n }\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */ async Jc() {\n if (0 !== this.Lc.length) {\n try {\n await this.Lc[0](), this.Lc.shift(), this.xo.reset();\n } catch (t) {\n if (!Vt(t)) throw t;\n // Failure will be handled by AsyncQueue\n C(\"AsyncQueue\", \"Operation failed with retryable error: \" + t);\n }\n this.Lc.length > 0 && \n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.xo.Ro((() => this.Jc()));\n }\n }\n Hc(t) {\n const e = this.Bc.then((() => (this.Gc = !0, t().catch((t => {\n this.Kc = t, this.Gc = !1;\n const e = \n /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n function(t) {\n let e = t.message || \"\";\n t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + \"\\n\" + t.stack);\n return e;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t);\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw x(\"INTERNAL UNHANDLED ERROR: \", e), t;\n })).then((t => (this.Gc = !1, t))))));\n return this.Bc = e, e;\n }\n enqueueAfterDelay(t, e, n) {\n this.zc(), \n // Fast-forward delays for timerIds that have been overriden.\n this.jc.indexOf(t) > -1 && (e = 0);\n const s = nc.createAndSchedule(this, t, e, n, (t => this.Yc(t)));\n return this.Uc.push(s), s;\n }\n zc() {\n this.Kc && O();\n }\n verifyOperationInProgress() {}\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */ async Xc() {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let t;\n do {\n t = this.Bc, await t;\n } while (t !== this.Bc);\n }\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */ Zc(t) {\n for (const e of this.Uc) if (e.timerId === t) return !0;\n return !1;\n }\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */ ta(t) {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.Xc().then((() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.Uc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));\n for (const e of this.Uc) if (e.skipDelay(), \"all\" /* TimerId.All */ !== t && e.timerId === t) break;\n return this.Xc();\n }));\n }\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */ ea(t) {\n this.jc.push(t);\n }\n /** Called once a DelayedOperation is run or canceled. */ Yc(t) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const e = this.Uc.indexOf(t);\n this.Uc.splice(e, 1);\n }\n}\n\nfunction eh(t) {\n /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n return function(t, e) {\n if (\"object\" != typeof t || null === t) return !1;\n const n = t;\n for (const t of e) if (t in n && \"function\" == typeof n[t]) return !0;\n return !1;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise<LoadBundleTaskProgress>`.\n */ (t, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass nh {\n constructor() {\n this._progressObserver = {}, this._taskCompletionResolver = new q, this._lastProgress = {\n taskState: \"Running\",\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n }\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */ onProgress(t, e, n) {\n this._progressObserver = {\n next: t,\n error: e,\n complete: n\n };\n }\n /**\n * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */ catch(t) {\n return this._taskCompletionResolver.promise.catch(t);\n }\n /**\n * Implements the `Promise<LoadBundleTaskProgress>.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */ then(t, e) {\n return this._taskCompletionResolver.promise.then(t, e);\n }\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */ _completeWith(t) {\n this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(), \n this._taskCompletionResolver.resolve(t);\n }\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */ _failWith(t) {\n this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);\n }\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */ _updateProgress(t) {\n this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** DOMException error code constants. */ const sh = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nclass ih extends ma {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n super(t, e, n, s), \n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n this.type = \"firestore\", this._queue = new th, this._persistenceKey = (null == s ? void 0 : s.name) || \"[DEFAULT]\";\n }\n _terminate() {\n return this._firestoreClient || \n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n ch(this), this._firestoreClient.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of database.\n * @returns A newly initialized {@link Firestore} instance.\n */ function rh(t, e, n) {\n n || (n = \"(default)\");\n const s = _getProvider(t, \"firestore\");\n if (s.isInitialized(n)) {\n const t = s.getImmediate({\n identifier: n\n }), i = s.getOptions(n);\n if (_(i, e)) return t;\n throw new L(B.FAILED_PRECONDITION, \"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.\");\n }\n if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new L(B.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n return s.initialize({\n options: e,\n instanceIdentifier: n\n });\n}\n\nfunction oh(e, n) {\n const s = \"object\" == typeof e ? e : t(), i = \"string\" == typeof e ? e : n || \"(default)\", r = _getProvider(s, \"firestore\").getImmediate({\n identifier: i\n });\n if (!r._initialized) {\n const t = w(\"firestore\");\n t && ga(r, ...t);\n }\n return r;\n}\n\n/**\n * @internal\n */ function uh(t) {\n return t._firestoreClient || ch(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;\n}\n\nfunction ch(t) {\n var e;\n const n = t._freezeSettings(), s = function(t, e, n, s) {\n return new Mt(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // settings() defaults:\n (t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || \"\", t._persistenceKey, n);\n t._firestoreClient = new ka(t._authCredentials, t._appCheckCredentials, t._queue, s);\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n */ function ah(t, e) {\n ph(t = fa(t, ih));\n const n = uh(t), s = t._freezeSettings(), i = new oa;\n return lh(n, i, new ia(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n */ function hh(t) {\n ph(t = fa(t, ih));\n const e = uh(t), n = t._freezeSettings(), s = new oa;\n return lh(e, s, new ra(s, n.cacheSizeBytes));\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function lh(t, e, n) {\n const s = new q;\n return t.asyncQueue.enqueue((async () => {\n try {\n await Oa(t, n), await Ma(t, e), s.resolve();\n } catch (t) {\n const e = t;\n if (!\n /**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\n function(t) {\n if (\"FirebaseError\" === t.name) return t.code === B.FAILED_PRECONDITION || t.code === B.UNIMPLEMENTED;\n if (\"undefined\" != typeof DOMException && t instanceof DOMException) \n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n return 22 === t.code || 20 === t.code || \n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n 11 === t.code;\n return !0;\n }\n /**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ (e)) throw e;\n N(\"Error enabling offline persistence. Falling back to persistence disabled: \" + e), \n s.reject(e);\n }\n })).then((() => s.promise));\n}\n\nfunction fh(t) {\n if (t._initialized && !t._terminated) throw new L(B.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n const e = new q;\n return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n await async function(t) {\n if (!bt.C()) return Promise.resolve();\n const e = t + \"main\";\n await bt.delete(e);\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */ (Fo(t._databaseId, t._persistenceKey)), e.resolve();\n } catch (t) {\n e.reject(t);\n }\n })), e.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function dh(t) {\n return function(t) {\n const e = new q;\n return t.asyncQueue.enqueueAndForget((async () => kc(await Ua(t), e))), e.promise;\n }(uh(t = fa(t, ih)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function _h(t) {\n return Qa(uh(t = fa(t, ih)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function wh(t) {\n return ja(uh(t = fa(t, ih)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function mh(t) {\n return e(t.app, \"firestore\", t._databaseId.database), t._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */ function gh(t, e) {\n const n = uh(t = fa(t, ih)), s = new nh;\n return Xa(n, t._databaseId, e, s), s;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function yh(t, e) {\n return Za(uh(t = fa(t, ih)), e).then((e => e ? new pa(t, null, e.query) : null));\n}\n\nfunction ph(t) {\n if (t._initialized || t._terminated) throw new L(B.FAILED_PRECONDITION, \"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing an array of bytes.\n */\nclass Ih {\n /** @hideconstructor */\n constructor(t) {\n this._byteString = t;\n }\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */ static fromBase64String(t) {\n try {\n return new Ih(Qt.fromBase64String(t));\n } catch (t) {\n throw new L(B.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + t);\n }\n }\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */ static fromUint8Array(t) {\n return new Ih(Qt.fromUint8Array(t));\n }\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */ toBase64() {\n return this._byteString.toBase64();\n }\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */ toUint8Array() {\n return this._byteString.toUint8Array();\n }\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */ toString() {\n return \"Bytes(base64: \" + this.toBase64() + \")\";\n }\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */ isEqual(t) {\n return this._byteString.isEqual(t._byteString);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */ class Th {\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...t) {\n for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new L(B.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n this._internalPath = new ut(t);\n }\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */ isEqual(t) {\n return this._internalPath.isEqual(t._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function Eh() {\n return new Th(\"__name__\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class Ah {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(t) {\n this._methodName = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class Rh {\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(t, e) {\n if (!isFinite(t) || t < -90 || t > 90) throw new L(B.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + t);\n if (!isFinite(e) || e < -180 || e > 180) throw new L(B.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + e);\n this._lat = t, this._long = e;\n }\n /**\n * The latitude of this `GeoPoint` instance.\n */ get latitude() {\n return this._lat;\n }\n /**\n * The longitude of this `GeoPoint` instance.\n */ get longitude() {\n return this._long;\n }\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */ isEqual(t) {\n return this._lat === t._lat && this._long === t._long;\n }\n /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */ _compareTo(t) {\n return Z(this._lat, t._lat) || Z(this._long, t._long);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const bh = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class Ph {\n constructor(t, e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return null !== this.fieldMask ? new ts(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Zn(t, this.data, e, this.fieldTransforms);\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class vh {\n constructor(t, \n // The fieldMask does not include document transforms.\n e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return new ts(t, this.data, this.fieldMask, e, this.fieldTransforms);\n }\n}\n\nfunction Vh(t) {\n switch (t) {\n case 0 /* UserDataSource.Set */ :\n // fall through\n case 2 /* UserDataSource.MergeSet */ :\n // fall through\n case 1 /* UserDataSource.Update */ :\n return !0;\n\n case 3 /* UserDataSource.Argument */ :\n case 4 /* UserDataSource.ArrayArgument */ :\n return !1;\n\n default:\n throw O();\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class Sh {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(t, e, n, s, i, r) {\n this.settings = t, this.databaseId = e, this.yt = n, this.ignoreUndefinedProperties = s, \n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n void 0 === i && this.na(), this.fieldTransforms = i || [], this.fieldMask = r || [];\n }\n get path() {\n return this.settings.path;\n }\n get sa() {\n return this.settings.sa;\n }\n /** Returns a new context with the specified settings overwritten. */ ia(t) {\n return new Sh(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.yt, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n }\n ra(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({\n path: n,\n oa: !1\n });\n return s.ua(t), s;\n }\n ca(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({\n path: n,\n oa: !1\n });\n return s.na(), s;\n }\n aa(t) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.ia({\n path: void 0,\n oa: !0\n });\n }\n ha(t) {\n return Hh(t, this.settings.methodName, this.settings.la || !1, this.path, this.settings.fa);\n }\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {\n return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));\n }\n na() {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path) for (let t = 0; t < this.path.length; t++) this.ua(this.path.get(t));\n }\n ua(t) {\n if (0 === t.length) throw this.ha(\"Document fields must not be empty\");\n if (Vh(this.sa) && bh.test(t)) throw this.ha('Document fields cannot begin and end with \"__\"');\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class Dh {\n constructor(t, e, n) {\n this.databaseId = t, this.ignoreUndefinedProperties = e, this.yt = n || pu(t);\n }\n /** Creates a new top-level parse context. */ da(t, e, n, s = !1) {\n return new Sh({\n sa: t,\n methodName: e,\n fa: n,\n path: ut.emptyPath(),\n oa: !1,\n la: s\n }, this.databaseId, this.yt, this.ignoreUndefinedProperties);\n }\n}\n\nfunction Ch(t) {\n const e = t._freezeSettings(), n = pu(t._databaseId);\n return new Dh(t._databaseId, !!e.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function xh(t, e, n, s, i, r = {}) {\n const o = t.da(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);\n Qh(\"Data must be an object, but it was:\", o, s);\n const u = Kh(s, o);\n let c, a;\n if (r.merge) c = new Je(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {\n const t = [];\n for (const s of r.mergeFields) {\n const i = jh(e, s, n);\n if (!o.contains(i)) throw new L(B.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n Jh(t, i) || t.push(i);\n }\n c = new Je(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));\n } else c = null, a = o.fieldTransforms;\n return new Ph(new Ye(u), c, a);\n}\n\nclass Nh extends Ah {\n _toFieldTransform(t) {\n if (2 /* UserDataSource.MergeSet */ !== t.sa) throw 1 /* UserDataSource.Update */ === t.sa ? t.ha(`${this._methodName}() can only appear at the top level of your update data`) : t.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n return t.fieldMask.push(t.path), null;\n }\n isEqual(t) {\n return t instanceof Nh;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function kh(t, e, n) {\n return new Sh({\n sa: 3 /* UserDataSource.Argument */ ,\n fa: e.settings.fa,\n methodName: t._methodName,\n oa: n\n }, e.databaseId, e.yt, e.ignoreUndefinedProperties);\n}\n\nclass Oh extends Ah {\n _toFieldTransform(t) {\n return new Un(t.path, new kn);\n }\n isEqual(t) {\n return t instanceof Oh;\n }\n}\n\nclass Mh extends Ah {\n constructor(t, e) {\n super(t), this._a = e;\n }\n _toFieldTransform(t) {\n const e = kh(this, t, \n /*array=*/ !0), n = this._a.map((t => Uh(t, e))), s = new On(n);\n return new Un(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass Fh extends Ah {\n constructor(t, e) {\n super(t), this._a = e;\n }\n _toFieldTransform(t) {\n const e = kh(this, t, \n /*array=*/ !0), n = this._a.map((t => Uh(t, e))), s = new Fn(n);\n return new Un(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass $h extends Ah {\n constructor(t, e) {\n super(t), this.wa = e;\n }\n _toFieldTransform(t) {\n const e = new Bn(t.yt, Sn(t.yt, this.wa));\n return new Un(t.path, e);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\n/** Parse update data from an update() call. */ function Bh(t, e, n, s) {\n const i = t.da(1 /* UserDataSource.Update */ , e, n);\n Qh(\"Data must be an object, but it was:\", i, s);\n const r = [], o = Ye.empty();\n Bt(s, ((t, s) => {\n const u = zh(e, t, n);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n s = d(s);\n const c = i.ca(u);\n if (s instanceof Nh) \n // Add it to the field mask, but don't add anything to updateData.\n r.push(u); else {\n const t = Uh(s, c);\n null != t && (r.push(u), o.set(u, t));\n }\n }));\n const u = new Je(r);\n return new vh(o, u, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function Lh(t, e, n, s, i, r) {\n const o = t.da(1 /* UserDataSource.Update */ , e, n), u = [ jh(e, s, n) ], c = [ i ];\n if (r.length % 2 != 0) throw new L(B.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);\n for (let t = 0; t < r.length; t += 2) u.push(jh(e, r[t])), c.push(r[t + 1]);\n const a = [], h = Ye.empty();\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let t = u.length - 1; t >= 0; --t) if (!Jh(a, u[t])) {\n const e = u[t];\n let n = c[t];\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n n = d(n);\n const s = o.ca(e);\n if (n instanceof Nh) \n // Add it to the field mask, but don't add anything to updateData.\n a.push(e); else {\n const t = Uh(n, s);\n null != t && (a.push(e), h.set(e, t));\n }\n }\n const l = new Je(a);\n return new vh(h, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function qh(t, e, n, s = !1) {\n return Uh(n, t.da(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function Uh(t, e) {\n if (Gh(\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n t = d(t))) return Qh(\"Unsupported field value:\", e, t), Kh(t, e);\n if (t instanceof Ah) \n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n return function(t, e) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!Vh(e.sa)) throw e.ha(`${t._methodName}() can only be used with update() and set()`);\n if (!e.path) throw e.ha(`${t._methodName}() is not currently supported inside arrays`);\n const n = t._toFieldTransform(e);\n n && e.fieldTransforms.push(n);\n }\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (t, e), null;\n if (void 0 === t && e.ignoreUndefinedProperties) \n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n if (\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n e.path && e.fieldMask.push(e.path), t instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (e.settings.oa && 4 /* UserDataSource.ArrayArgument */ !== e.sa) throw e.ha(\"Nested arrays are not supported\");\n return function(t, e) {\n const n = [];\n let s = 0;\n for (const i of t) {\n let t = Uh(i, e.aa(s));\n null == t && (\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n t = {\n nullValue: \"NULL_VALUE\"\n }), n.push(t), s++;\n }\n return {\n arrayValue: {\n values: n\n }\n };\n }(t, e);\n }\n return function(t, e) {\n if (null === (t = d(t))) return {\n nullValue: \"NULL_VALUE\"\n };\n if (\"number\" == typeof t) return Sn(e.yt, t);\n if (\"boolean\" == typeof t) return {\n booleanValue: t\n };\n if (\"string\" == typeof t) return {\n stringValue: t\n };\n if (t instanceof Date) {\n const n = nt.fromDate(t);\n return {\n timestampValue: $s(e.yt, n)\n };\n }\n if (t instanceof nt) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const n = new nt(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));\n return {\n timestampValue: $s(e.yt, n)\n };\n }\n if (t instanceof Rh) return {\n geoPointValue: {\n latitude: t.latitude,\n longitude: t.longitude\n }\n };\n if (t instanceof Ih) return {\n bytesValue: Bs(e.yt, t._byteString)\n };\n if (t instanceof ya) {\n const n = e.databaseId, s = t.firestore._databaseId;\n if (!s.isEqual(n)) throw e.ha(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);\n return {\n referenceValue: Us(t.firestore._databaseId || e.databaseId, t._key.path)\n };\n }\n throw e.ha(`Unsupported field value: ${la(t)}`);\n }\n /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (t, e);\n}\n\nfunction Kh(t, e) {\n const n = {};\n return Lt(t) ? \n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n e.path && e.path.length > 0 && e.fieldMask.push(e.path) : Bt(t, ((t, s) => {\n const i = Uh(s, e.ra(t));\n null != i && (n[t] = i);\n })), {\n mapValue: {\n fields: n\n }\n };\n}\n\nfunction Gh(t) {\n return !(\"object\" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof nt || t instanceof Rh || t instanceof Ih || t instanceof ya || t instanceof Ah);\n}\n\nfunction Qh(t, e, n) {\n if (!Gh(n) || !function(t) {\n return \"object\" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));\n }(n)) {\n const s = la(n);\n throw \"an object\" === s ? e.ha(t + \" a custom object\") : e.ha(t + \" \" + s);\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function jh(t, e, n) {\n if ((\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n e = d(e)) instanceof Th) return e._internalPath;\n if (\"string\" == typeof e) return zh(t, e);\n throw Hh(\"Field path arguments must be of type string or \", t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const Wh = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function zh(t, e, n) {\n if (e.search(Wh) >= 0) throw Hh(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n try {\n return new Th(...e.split(\".\"))._internalPath;\n } catch (s) {\n throw Hh(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n }\n}\n\nfunction Hh(t, e, n, s, i) {\n const r = s && !s.isEmpty(), o = void 0 !== i;\n let u = `Function ${e}() called with invalid data`;\n n && (u += \" (via `toFirestore()`)\"), u += \". \";\n let c = \"\";\n return (r || o) && (c += \" (found\", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`), \n c += \")\"), new L(B.INVALID_ARGUMENT, u + t + c);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Jh(t, e) {\n return t.some((t => t.isEqual(e)));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class Yh {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n /** @hideconstructor protected */\n constructor(t, e, n, s, i) {\n this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s, \n this._converter = i;\n }\n /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */ get ref() {\n return new ya(this._firestore, this._converter, this._key);\n }\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */ exists() {\n return null !== this._document;\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */ data() {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const t = new Xh(this._firestore, this._userDataWriter, this._key, this._document, \n /* converter= */ null);\n return this._converter.fromFirestore(t);\n }\n return this._userDataWriter.convertValue(this._document.data.value);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t) {\n if (this._document) {\n const e = this._document.data.field(Zh(\"DocumentSnapshot.get\", t));\n if (null !== e) return this._userDataWriter.convertValue(e);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class Xh extends Yh {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data() {\n return super.data();\n }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function Zh(t, e) {\n return \"string\" == typeof e ? zh(t, e) : e instanceof Th ? e._internalPath : e._delegate._internalPath;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function tl(t) {\n if (\"L\" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new L(B.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */ class el {}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link\n * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class nl extends el {}\n\nfunction sl(t, e, ...n) {\n let s = [];\n e instanceof el && s.push(e), s = s.concat(n), function(t) {\n const e = t.filter((t => t instanceof ol)).length, n = t.filter((t => t instanceof il)).length;\n if (e > 1 || e > 0 && n > 0) throw new L(B.INVALID_ARGUMENT, \"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.\");\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ (s);\n for (const e of s) t = e._apply(t);\n return t;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link query} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */ class il extends nl {\n /**\n * @internal\n */\n constructor(t, e, n) {\n super(), this._field = t, this._op = e, this._value = n, \n /** The type of this query constraint */\n this.type = \"where\";\n }\n static _create(t, e, n) {\n return new il(t, e, n);\n }\n _apply(t) {\n const e = this._parse(t);\n return Al(t._query, e), new pa(t.firestore, t.converter, yn(t._query, e));\n }\n _parse(t) {\n const e = Ch(t.firestore), n = function(t, e, n, s, i, r, o) {\n let u;\n if (i.isKeyField()) {\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === r || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new L(B.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);\n if (\"in\" /* Operator.IN */ === r || \"not-in\" /* Operator.NOT_IN */ === r) {\n El(o, r);\n const e = [];\n for (const n of o) e.push(Tl(s, t, n));\n u = {\n arrayValue: {\n values: e\n }\n };\n } else u = Tl(s, t, o);\n } else \"in\" /* Operator.IN */ !== r && \"not-in\" /* Operator.NOT_IN */ !== r && \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ !== r || El(o, r), \n u = qh(n, e, o, \n /* allowArrays= */ \"in\" /* Operator.IN */ === r || \"not-in\" /* Operator.NOT_IN */ === r);\n return Re.create(i, r, u);\n }(t._query, \"where\", e, t.firestore._databaseId, this._field, this._op, this._value);\n return n;\n }\n}\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"&lt;\", \"&lt;=\", \"==\", \"&lt;\",\n * \"&lt;=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */ function rl(t, e, n) {\n const s = e, i = Zh(\"where\", t);\n return il._create(i, s, n);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link query} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n * @internal TODO remove this internal tag with OR Query support in the server\n */ class ol extends el {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e) {\n super(), this.type = t, this._queryConstraints = e;\n }\n static _create(t, e) {\n return new ol(t, e);\n }\n _parse(t) {\n const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));\n return 1 === e.length ? e[0] : be.create(e, this._getOperator());\n }\n _apply(t) {\n const e = this._parse(t);\n return 0 === e.getFilters().length ? t : (function(t, e) {\n let n = t;\n const s = e.getFlattenedFilters();\n for (const t of s) Al(n, t), n = yn(n, t);\n }\n // Checks if any of the provided filter operators are included in the given list of filters and\n // returns the first one that is, or null if none are.\n (t._query, e), new pa(t.firestore, t.converter, yn(t._query, e)));\n }\n _getQueryConstraints() {\n return this._queryConstraints;\n }\n _getOperator() {\n return \"and\" === this.type ? \"and\" /* CompositeOperator.AND */ : \"or\" /* CompositeOperator.OR */;\n }\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n * @internal TODO remove this internal tag with OR Query support in the server\n */ function ul(...t) {\n // Only support QueryFilterConstraints\n return t.forEach((t => bl(\"or\", t))), ol._create(\"or\" /* CompositeOperator.OR */ , t);\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n * @internal TODO remove this internal tag with OR Query support in the server\n */ function cl(...t) {\n // Only support QueryFilterConstraints\n return t.forEach((t => bl(\"and\", t))), ol._create(\"and\" /* CompositeOperator.AND */ , t);\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link query} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */ class al extends nl {\n /**\n * @internal\n */\n constructor(t, e) {\n super(), this._field = t, this._direction = e, \n /** The type of this query constraint */\n this.type = \"orderBy\";\n }\n static _create(t, e) {\n return new al(t, e);\n }\n _apply(t) {\n const e = function(t, e, n) {\n if (null !== t.startAt) throw new L(B.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n if (null !== t.endAt) throw new L(B.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n const s = new Ue(e, n);\n return function(t, e) {\n if (null === dn(t)) {\n // This is the first order by. It must match any inequality.\n const n = _n(t);\n null !== n && Rl(t, n, e.field);\n }\n }(t, s), s;\n }\n /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (t._query, this._field, this._direction);\n return new pa(t.firestore, t.converter, function(t, e) {\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const n = t.explicitOrderBy.concat([ e ]);\n return new an(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(t._query, e));\n }\n}\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */ function hl(t, e = \"asc\") {\n const n = e, s = Zh(\"orderBy\", t);\n return al._create(s, n);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link query} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */ class ll extends nl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._limit = e, this._limitType = n;\n }\n static _create(t, e, n) {\n return new ll(t, e, n);\n }\n _apply(t) {\n return new pa(t.firestore, t.converter, pn(t._query, this._limit, this._limitType));\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function fl(t) {\n return da(\"limit\", t), ll._create(\"limit\", t, \"F\" /* LimitType.First */);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function dl(t) {\n return da(\"limitToLast\", t), ll._create(\"limitToLast\", t, \"L\" /* LimitType.Last */);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link query} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */ class _l extends nl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._docOrFields = e, this._inclusive = n;\n }\n static _create(t, e, n) {\n return new _l(t, e, n);\n }\n _apply(t) {\n const e = Il(t, this.type, this._docOrFields, this._inclusive);\n return new pa(t.firestore, t.converter, function(t, e) {\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);\n }(t._query, e));\n }\n}\n\nfunction wl(...t) {\n return _l._create(\"startAt\", t, \n /*inclusive=*/ !0);\n}\n\nfunction ml(...t) {\n return _l._create(\"startAfter\", t, \n /*inclusive=*/ !1);\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link query} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */ class gl extends nl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._docOrFields = e, this._inclusive = n;\n }\n static _create(t, e, n) {\n return new gl(t, e, n);\n }\n _apply(t) {\n const e = Il(t, this.type, this._docOrFields, this._inclusive);\n return new pa(t.firestore, t.converter, function(t, e) {\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);\n }(t._query, e));\n }\n}\n\nfunction yl(...t) {\n return gl._create(\"endBefore\", t, \n /*inclusive=*/ !1);\n}\n\nfunction pl(...t) {\n return gl._create(\"endAt\", t, \n /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function Il(t, e, n, s) {\n if (n[0] = d(n[0]), n[0] instanceof Yh) return function(t, e, n, s, i) {\n if (!s) throw new L(B.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n const r = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const n of mn(t)) if (n.field.isKeyField()) r.push(ce(e, s.key)); else {\n const t = s.data.field(n.field);\n if (Jt(t)) throw new L(B.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field \"' + n.field + '\" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');\n if (null === t) {\n const t = n.field.canonicalString();\n throw new L(B.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);\n }\n r.push(t);\n }\n return new Ie(r, i);\n }\n /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (t._query, t.firestore._databaseId, e, n[0]._document, s);\n {\n const i = Ch(t.firestore);\n return function(t, e, n, s, i, r) {\n // Use explicit order by's because it has to match the query the user made\n const o = t.explicitOrderBy;\n if (i.length > o.length) throw new L(B.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n const u = [];\n for (let r = 0; r < i.length; r++) {\n const c = i[r];\n if (o[r].field.isKeyField()) {\n if (\"string\" != typeof c) throw new L(B.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);\n if (!wn(t) && -1 !== c.indexOf(\"/\")) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);\n const n = t.path.child(rt.fromString(c));\n if (!ct.isDocumentKey(n)) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n const i = new ct(n);\n u.push(ce(e, i));\n } else {\n const t = qh(n, s, c);\n u.push(t);\n }\n }\n return new Ie(u, r);\n }\n /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (t._query, t.firestore._databaseId, i, e, n, s);\n }\n}\n\nfunction Tl(t, e, n) {\n if (\"string\" == typeof (n = d(n))) {\n if (\"\" === n) throw new L(B.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n if (!wn(e) && -1 !== n.indexOf(\"/\")) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n const s = e.path.child(rt.fromString(n));\n if (!ct.isDocumentKey(s)) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);\n return ce(t, new ct(s));\n }\n if (n instanceof ya) return ce(t, n._key);\n throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${la(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function El(t, e) {\n if (!Array.isArray(t) || 0 === t.length) throw new L(B.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);\n if (t.length > 10) throw new L(B.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one array operator is allowed.\n * 2. Only one disjunctive operator is allowed.\n * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.\n * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n *\n * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`\n * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`\n */ function Al(t, e) {\n if (e.isInequality()) {\n const n = _n(t), s = e.field;\n if (null !== n && !n.isEqual(s)) throw new L(B.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);\n const i = dn(t);\n null !== i && Rl(t, s, i);\n }\n const n = function(t, e) {\n for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;\n return null;\n }(t.filters, function(t) {\n switch (t) {\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return [ \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ \"array-contains\" /* Operator.ARRAY_CONTAINS */ , \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"in\" /* Operator.IN */ :\n return [ \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return [ \"array-contains\" /* Operator.ARRAY_CONTAINS */ , \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"not-in\" /* Operator.NOT_IN */ :\n return [ \"array-contains\" /* Operator.ARRAY_CONTAINS */ , \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ , \"!=\" /* Operator.NOT_EQUAL */ ];\n\n default:\n return [];\n }\n }(e.op));\n if (null !== n) \n // Special case when it's a duplicate op to give a slightly clearer error message.\n throw n === e.op ? new L(B.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new L(B.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);\n}\n\nfunction Rl(t, e, n) {\n if (!n.isEqual(e)) throw new L(B.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);\n}\n\nfunction bl(t, e) {\n if (!(e instanceof il || e instanceof ol)) throw new L(B.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);\n}\n\nclass Pl {\n convertValue(t, e = \"none\") {\n switch (ee(t)) {\n case 0 /* TypeOrder.NullValue */ :\n return null;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return t.booleanValue;\n\n case 2 /* TypeOrder.NumberValue */ :\n return zt(t.integerValue || t.doubleValue);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return this.convertTimestamp(t.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return this.convertServerTimestamp(t, e);\n\n case 5 /* TypeOrder.StringValue */ :\n return t.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return this.convertBytes(Ht(t.bytesValue));\n\n case 7 /* TypeOrder.RefValue */ :\n return this.convertReference(t.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return this.convertGeoPoint(t.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return this.convertArray(t.arrayValue, e);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return this.convertObject(t.mapValue, e);\n\n default:\n throw O();\n }\n }\n convertObject(t, e) {\n const n = {};\n return Bt(t.fields, ((t, s) => {\n n[t] = this.convertValue(s, e);\n })), n;\n }\n convertGeoPoint(t) {\n return new Rh(zt(t.latitude), zt(t.longitude));\n }\n convertArray(t, e) {\n return (t.values || []).map((t => this.convertValue(t, e)));\n }\n convertServerTimestamp(t, e) {\n switch (e) {\n case \"previous\":\n const n = Yt(t);\n return null == n ? null : this.convertValue(n, e);\n\n case \"estimate\":\n return this.convertTimestamp(Xt(t));\n\n default:\n return null;\n }\n }\n convertTimestamp(t) {\n const e = Wt(t);\n return new nt(e.seconds, e.nanos);\n }\n convertDocumentKey(t, e) {\n const n = rt.fromString(t);\n M(wi(n));\n const s = new Ft(n.get(1), n.get(3)), i = new ct(n.popFirst(5));\n return s.isEqual(e) || \n // TODO(b/64130202): Somehow support foreign references.\n x(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), \n i;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function vl(t, e, n) {\n let s;\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e, \n s;\n}\n\nclass Vl extends Pl {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new Ih(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new ya(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */ class Sl {\n /** @hideconstructor */\n constructor(t, e) {\n this.hasPendingWrites = t, this.fromCache = e;\n }\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */ isEqual(t) {\n return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;\n }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class Dl extends Yh {\n /** @hideconstructor protected */\n constructor(t, e, n, s, i, r) {\n super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;\n }\n /**\n * Returns whether or not the data exists. True if the document exists.\n */ exists() {\n return super.exists();\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */ data(t = {}) {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const e = new Cl(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n /* converter= */ null);\n return this._converter.fromFirestore(e, t);\n }\n return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t, e = {}) {\n if (this._document) {\n const n = this._document.data.field(Zh(\"DocumentSnapshot.get\", t));\n if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class Cl extends Dl {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(t = {}) {\n return super.data(t);\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class xl {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new Sl(s.hasPendingWrites, s.fromCache), \n this.query = n;\n }\n /** An array of all the documents in the `QuerySnapshot`. */ get docs() {\n const t = [];\n return this.forEach((e => t.push(e))), t;\n }\n /** The number of documents in the `QuerySnapshot`. */ get size() {\n return this._snapshot.docs.size;\n }\n /** True if there are no documents in the `QuerySnapshot`. */ get empty() {\n return 0 === this.size;\n }\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */ forEach(t, e) {\n this._snapshot.docs.forEach((n => {\n t.call(e, new Cl(this._firestore, this._userDataWriter, n.key, n, new Sl(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n }));\n }\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */ docChanges(t = {}) {\n const e = !!t.includeMetadataChanges;\n if (e && this._snapshot.excludesMetadataChanges) throw new L(B.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges = \n /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n function(t, e) {\n if (t._snapshot.oldDocs.isEmpty()) {\n let e = 0;\n return t._snapshot.docChanges.map((n => {\n const s = new Cl(t._firestore, t._userDataWriter, n.doc.key, n.doc, new Sl(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);\n return n.doc, {\n type: \"added\",\n doc: s,\n oldIndex: -1,\n newIndex: e++\n };\n }));\n }\n {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let n = t._snapshot.oldDocs;\n return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {\n const s = new Cl(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Sl(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);\n let i = -1, r = -1;\n return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), \n 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)), \n {\n type: Nl(e.type),\n doc: s,\n oldIndex: i,\n newIndex: r\n };\n }));\n }\n }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;\n }\n}\n\nfunction Nl(t) {\n switch (t) {\n case 0 /* ChangeType.Added */ :\n return \"added\";\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n return \"modified\";\n\n case 1 /* ChangeType.Removed */ :\n return \"removed\";\n\n default:\n return O();\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function kl(t, e) {\n return t instanceof Dl && e instanceof Dl ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof xl && e instanceof xl && (t._firestore === e._firestore && ba(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function Ol(t) {\n t = fa(t, ya);\n const e = fa(t.firestore, ih);\n return za(uh(e), t._key).then((n => Hl(e, t, n)));\n}\n\nclass Ml extends Pl {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new Ih(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new ya(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function Fl(t) {\n t = fa(t, ya);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return Wa(n, t._key).then((n => new Dl(e, s, t._key, n, new Sl(null !== n && n.hasLocalMutations, \n /* fromCache= */ !0), t.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function $l(t) {\n t = fa(t, ya);\n const e = fa(t.firestore, ih);\n return za(uh(e), t._key, {\n source: \"server\"\n }).then((n => Hl(e, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function Bl(t) {\n t = fa(t, pa);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return tl(t._query), Ja(n, t._query).then((n => new xl(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function Ll(t) {\n t = fa(t, pa);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return Ha(n, t._query).then((n => new xl(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function ql(t) {\n t = fa(t, pa);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return Ja(n, t._query, {\n source: \"server\"\n }).then((n => new xl(e, s, t, n)));\n}\n\nfunction Ul(t, e, n) {\n t = fa(t, ya);\n const s = fa(t.firestore, ih), i = vl(t.converter, e, n);\n return zl(s, [ xh(Ch(s), \"setDoc\", t._key, i, null !== t.converter, n).toMutation(t._key, Qn.none()) ]);\n}\n\nfunction Kl(t, e, n, ...s) {\n t = fa(t, ya);\n const i = fa(t.firestore, ih), r = Ch(i);\n let o;\n o = \"string\" == typeof (\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n e = d(e)) || e instanceof Th ? Lh(r, \"updateDoc\", t._key, e, n, s) : Bh(r, \"updateDoc\", t._key, e);\n return zl(i, [ o.toMutation(t._key, Qn.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function Gl(t) {\n return zl(fa(t.firestore, ih), [ new is(t._key, Qn.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function Ql(t, e) {\n const n = fa(t.firestore, ih), s = Aa(t), i = vl(t.converter, e);\n return zl(n, [ xh(Ch(t.firestore), \"addDoc\", s._key, i, null !== t.converter, {}).toMutation(s._key, Qn.exists(!1)) ]).then((() => s));\n}\n\nfunction jl(t, ...e) {\n var n, s, i;\n t = d(t);\n let r = {\n includeMetadataChanges: !1\n }, o = 0;\n \"object\" != typeof e[o] || eh(e[o]) || (r = e[o], o++);\n const u = {\n includeMetadataChanges: r.includeMetadataChanges\n };\n if (eh(e[o])) {\n const t = e[o];\n e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t), \n e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);\n }\n let c, a, h;\n if (t instanceof ya) a = fa(t.firestore, ih), h = ln(t._key.path), c = {\n next: n => {\n e[o] && e[o](Hl(a, t, n));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }; else {\n const n = fa(t, pa);\n a = fa(n.firestore, ih), h = n._query;\n const s = new Ml(a);\n c = {\n next: t => {\n e[o] && e[o](new xl(a, s, n, t));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }, tl(t._query);\n }\n return function(t, e, n, s) {\n const i = new va(s), r = new _c(e, i, n);\n return t.asyncQueue.enqueueAndForget((async () => ac(await Ga(t), r))), () => {\n i.bc(), t.asyncQueue.enqueueAndForget((async () => hc(await Ga(t), r)));\n };\n }(uh(a), h, u, c);\n}\n\nfunction Wl(t, e) {\n return Ya(uh(t = fa(t, ih)), eh(e) ? e : {\n next: e\n });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function zl(t, e) {\n return function(t, e) {\n const n = new q;\n return t.asyncQueue.enqueueAndForget((async () => Vc(await Ua(t), e, n))), n.promise;\n }(uh(t), e);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function Hl(t, e, n) {\n const s = n.docs.get(e._key), i = new Ml(t);\n return new Dl(t, i, e._key, s, new Sl(n.hasPendingWrites, n.fromCache), e.converter);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */ function Jl(t, e) {\n return ba(t.query, e.query) && _(t.data(), e.data());\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Calculates the number of documents in the result set of the given query,\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can even\n * count the documents if the result set would be prohibitively large to\n * download entirely (e.g. thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used: every request using this source necessarily involves a round trip to\n * the server.\n *\n * @param query - The query whose result set size to calculate.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */ function Yl(t) {\n const e = fa(t.firestore, ih);\n return function(t, e, n) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => {\n try {\n if (Mu(await qa(t))) {\n const i = await Ka(t), r = new Ca(e, i, n).run();\n s.resolve(r);\n } else s.reject(new L(B.UNAVAILABLE, \"Failed to get count result because the client is offline.\"));\n } catch (t) {\n s.reject(t);\n }\n })), s.promise;\n }(uh(e), t, new Ml(e));\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Xl = {\n maxAttempts: 5\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nclass Zl {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, \n this._dataReader = Ch(t);\n }\n set(t, e, n) {\n this._verifyNotCommitted();\n const s = tf(t, this._firestore), i = vl(s.converter, e, n), r = xh(this._dataReader, \"WriteBatch.set\", s._key, i, null !== s.converter, n);\n return this._mutations.push(r.toMutation(s._key, Qn.none())), this;\n }\n update(t, e, n, ...s) {\n this._verifyNotCommitted();\n const i = tf(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = d(e)) || e instanceof Th ? Lh(this._dataReader, \"WriteBatch.update\", i._key, e, n, s) : Bh(this._dataReader, \"WriteBatch.update\", i._key, e), \n this._mutations.push(r.toMutation(i._key, Qn.exists(!0))), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */ delete(t) {\n this._verifyNotCommitted();\n const e = tf(t, this._firestore);\n return this._mutations = this._mutations.concat(new is(e._key, Qn.none())), this;\n }\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */ commit() {\n return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n }\n _verifyNotCommitted() {\n if (this._committed) throw new L(B.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n }\n}\n\nfunction tf(t, e) {\n if ((t = d(t)).firestore !== e) throw new L(B.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n return t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nclass ef extends class {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._transaction = e, this._dataReader = Ch(t);\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = tf(t, this._firestore), n = new Vl(this._firestore);\n return this._transaction.lookup([ e._key ]).then((t => {\n if (!t || 1 !== t.length) return O();\n const s = t[0];\n if (s.isFoundDocument()) return new Yh(this._firestore, n, s.key, s, e.converter);\n if (s.isNoDocument()) return new Yh(this._firestore, n, e._key, null, e.converter);\n throw O();\n }));\n }\n set(t, e, n) {\n const s = tf(t, this._firestore), i = vl(s.converter, e, n), r = xh(this._dataReader, \"Transaction.set\", s._key, i, null !== s.converter, n);\n return this._transaction.set(s._key, r), this;\n }\n update(t, e, n, ...s) {\n const i = tf(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = d(e)) || e instanceof Th ? Lh(this._dataReader, \"Transaction.update\", i._key, e, n, s) : Bh(this._dataReader, \"Transaction.update\", i._key, e), \n this._transaction.update(i._key, r), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */ delete(t) {\n const e = tf(t, this._firestore);\n return this._transaction.delete(e._key), this;\n }\n} {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n /** @hideconstructor */\n constructor(t, e) {\n super(t, e), this._firestore = t;\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = tf(t, this._firestore), n = new Ml(this._firestore);\n return super.get(t).then((t => new Dl(this._firestore, n, e._key, t._document, new Sl(\n /* hasPendingWrites= */ !1, \n /* fromCache= */ !1), e.converter)));\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function nf(t, e, n) {\n t = fa(t, ih);\n const s = Object.assign(Object.assign({}, Xl), n);\n !function(t) {\n if (t.maxAttempts < 1) throw new L(B.INVALID_ARGUMENT, \"Max attempts must be at least 1\");\n }(s);\n return function(t, e, n) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => {\n const i = await Ka(t);\n new Na(t.asyncQueue, i, n, e, s).run();\n })), s.promise;\n }(uh(t), (n => e(new ef(t, n))), s);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function sf() {\n return new Nh(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function rf() {\n return new Oh(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function of(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new Mh(\"arrayUnion\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function uf(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new Fh(\"arrayRemove\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function cf(t) {\n return new $h(\"increment\", t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function af(t) {\n return uh(t = fa(t, ih)), new Zl(t, (e => zl(t, e)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function hf(t, e) {\n var n;\n const s = uh(t = fa(t, ih));\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n if (!(null === (n = s.offlineComponents) || void 0 === n ? void 0 : n.indexBackfillerScheduler)) return N(\"Cannot enable indexes when persistence is disabled\"), \n Promise.resolve();\n const i = function(t) {\n const e = \"string\" == typeof t ? function(t) {\n try {\n return JSON.parse(t);\n } catch (t) {\n throw new L(B.INVALID_ARGUMENT, \"Failed to parse JSON: \" + (null == t ? void 0 : t.message));\n }\n }(t) : t, n = [];\n if (Array.isArray(e.indexes)) for (const t of e.indexes) {\n const e = lf(t, \"collectionGroup\"), s = [];\n if (Array.isArray(t.fields)) for (const e of t.fields) {\n const t = zh(\"setIndexConfiguration\", lf(e, \"fieldPath\"));\n \"CONTAINS\" === e.arrayConfig ? s.push(new dt(t, 2 /* IndexKind.CONTAINS */)) : \"ASCENDING\" === e.order ? s.push(new dt(t, 0 /* IndexKind.ASCENDING */)) : \"DESCENDING\" === e.order && s.push(new dt(t, 1 /* IndexKind.DESCENDING */));\n }\n n.push(new at(at.UNKNOWN_ID, e, s, wt.empty()));\n }\n return n;\n }(e);\n return La(s).then((t => async function(t, e) {\n const n = $(t), s = n.indexManager, i = [];\n return n.persistence.runTransaction(\"Configure indexes\", \"readwrite\", (t => s.getFieldIndexes(t).next((n => function(t, e, n, s, i) {\n t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);\n const r = t.length, o = e.length;\n let u = 0, c = 0;\n for (;u < o && c < r; ) {\n const r = n(t[c], e[u]);\n r < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n i(t[c++]) : r > 0 ? \n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n s(e[u++]) : (u++, c++);\n }\n for (;u < o; ) s(e[u++]);\n for (;c < r; ) i(t[c++]);\n }(n, e, ft, (e => {\n i.push(s.addFieldIndex(t, e));\n }), (e => {\n i.push(s.deleteFieldIndex(t, e));\n })))).next((() => At.waitFor(i)))));\n }\n /**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // The format of the LocalStorage key that stores the client state is:\n // firestore_clients_<persistence_prefix>_<instance_key>\n (t, i)));\n}\n\nfunction lf(t, e) {\n if (\"string\" != typeof t[e]) throw new L(B.INVALID_ARGUMENT, \"Missing string value for: \" + e);\n return t[e];\n}\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function(t, e = !0) {\n !function(t) {\n v = t;\n }(i), n(new r(\"firestore\", ((t, {instanceIdentifier: n, options: s}) => {\n const i = t.getProvider(\"app\").getImmediate(), r = new ih(new Q(t.getProvider(\"auth-internal\")), new H(t.getProvider(\"app-check-internal\")), function(t, e) {\n if (!Object.prototype.hasOwnProperty.apply(t.options, [ \"projectId\" ])) throw new L(B.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n return new Ft(t.options.projectId, e);\n }(i, n), i);\n return s = Object.assign({\n useFetchStreams: e\n }, s), r._setSettings(s), r;\n }), \"PUBLIC\").setMultipleInstances(!0)), s(b, \"3.8.1\", t), \n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n s(b, \"3.8.1\", \"__BUILD_TARGET__\");\n}();\n\nexport { Pl as AbstractUserDataWriter, Sa as AggregateField, Da as AggregateQuerySnapshot, Ih as Bytes, sh as CACHE_SIZE_UNLIMITED, Ia as CollectionReference, ya as DocumentReference, Dl as DocumentSnapshot, Th as FieldPath, Ah as FieldValue, ih as Firestore, L as FirestoreError, Rh as GeoPoint, nh as LoadBundleTask, pa as Query, ol as QueryCompositeFilterConstraint, nl as QueryConstraint, Cl as QueryDocumentSnapshot, gl as QueryEndAtConstraint, il as QueryFieldFilterConstraint, ll as QueryLimitConstraint, al as QueryOrderByConstraint, xl as QuerySnapshot, _l as QueryStartAtConstraint, Sl as SnapshotMetadata, nt as Timestamp, ef as Transaction, Zl as WriteBatch, Ft as _DatabaseId, ct as _DocumentKey, J as _EmptyAppCheckTokenProvider, K as _EmptyAuthCredentialsProvider, ut as _FieldPath, fa as _cast, F as _debugAssert, Gt as _isBase64Available, N as _logWarn, ca as _validateIsNotUsedTogether, Ql as addDoc, Jl as aggregateQuerySnapshotEqual, cl as and, uf as arrayRemove, of as arrayUnion, fh as clearIndexedDbPersistence, Ta as collection, Ea as collectionGroup, ga as connectFirestoreEmulator, Gl as deleteDoc, sf as deleteField, wh as disableNetwork, Aa as doc, Eh as documentId, ah as enableIndexedDbPersistence, hh as enableMultiTabIndexedDbPersistence, _h as enableNetwork, pl as endAt, yl as endBefore, uh as ensureFirestoreConfigured, zl as executeWrite, Yl as getCountFromServer, Ol as getDoc, Fl as getDocFromCache, $l as getDocFromServer, Bl as getDocs, Ll as getDocsFromCache, ql as getDocsFromServer, oh as getFirestore, cf as increment, rh as initializeFirestore, fl as limit, dl as limitToLast, gh as loadBundle, yh as namedQuery, jl as onSnapshot, Wl as onSnapshotsInSync, ul as or, hl as orderBy, sl as query, ba as queryEqual, Ra as refEqual, nf as runTransaction, rf as serverTimestamp, Ul as setDoc, hf as setIndexConfiguration, D as setLogLevel, kl as snapshotEqual, ml as startAfter, wl as startAt, mh as terminate, Kl as updateDoc, dh as waitForPendingWrites, rl as where, af as writeBatch };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\n * avoid exposing concrete classes to clients.\n */\n\ngoog.provide('goog.net.createWebChannelTransport');\n\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\ngoog.requireType('goog.net.WebChannelTransport');\n\n\n/**\n * Create a new WebChannelTransport instance using the default implementation.\n * Throws an error message if no default transport available in the current\n * environment.\n *\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\n */\ngoog.net.createWebChannelTransport = function() {\n 'use strict';\n return new goog.labs.net.webChannel.WebChannelBaseTransport();\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport type { FirebaseNamespace } from '@firebase/app-types';\nimport * as types from '@firebase/firestore-types';\n\nimport { name, version } from '../package.json';\n\nimport { Firestore, IndexedDbPersistenceProvider } from './api/database';\nimport { configureForFirebase } from './config';\n\nimport './register-module';\n\n/**\n * Registers the main Firestore build with the components framework.\n * Persistence can be enabled via `firebase.firestore().enablePersistence()`.\n */\nexport function registerFirestore(instance: FirebaseNamespace): void {\n configureForFirebase(\n instance,\n (app, firestoreExp) =>\n new Firestore(app, firestoreExp, new IndexedDbPersistenceProvider())\n );\n instance.registerVersion(name, version);\n}\n\nregisterFirestore(firebase as unknown as FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n firestore: {\n (app?: FirebaseApp): types.FirebaseFirestore;\n Blob: typeof types.Blob;\n CollectionReference: typeof types.CollectionReference;\n DocumentReference: typeof types.DocumentReference;\n DocumentSnapshot: typeof types.DocumentSnapshot;\n FieldPath: typeof types.FieldPath;\n FieldValue: typeof types.FieldValue;\n Firestore: typeof types.FirebaseFirestore;\n GeoPoint: typeof types.GeoPoint;\n Query: typeof types.Query;\n QueryDocumentSnapshot: typeof types.QueryDocumentSnapshot;\n QuerySnapshot: typeof types.QuerySnapshot;\n Timestamp: typeof types.Timestamp;\n Transaction: typeof types.Transaction;\n WriteBatch: typeof types.WriteBatch;\n setLogLevel: typeof types.setLogLevel;\n };\n }\n interface FirebaseApp {\n firestore?(): types.FirebaseFirestore;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { FirebaseApp } from '@firebase/app-compat';\nimport { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport {\n Firestore as ModularFirestore,\n CACHE_SIZE_UNLIMITED,\n GeoPoint,\n Timestamp\n} from '@firebase/firestore';\n\nimport { Blob } from './api/blob';\nimport {\n Firestore,\n Transaction,\n CollectionReference,\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n QuerySnapshot,\n WriteBatch,\n setLogLevel\n} from './api/database';\nimport { FieldPath } from './api/field_path';\nimport { FieldValue } from './api/field_value';\n\nconst firestoreNamespace = {\n Firestore,\n GeoPoint,\n Timestamp,\n Blob,\n Transaction,\n WriteBatch,\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n QuerySnapshot,\n CollectionReference,\n FieldPath,\n FieldValue,\n setLogLevel,\n CACHE_SIZE_UNLIMITED\n};\n\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerComponent.\n *\n * @param firebase - The FirebaseNamespace to register Firestore with\n * @param firestoreFactory - A factory function that returns a new Firestore\n * instance.\n */\nexport function configureForFirebase(\n firebase: FirebaseNamespace,\n firestoreFactory: (\n app: FirebaseApp,\n firestoreExp: ModularFirestore\n ) => Firestore\n): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'firestore-compat',\n container => {\n const app = container.getProvider('app-compat').getImmediate()!;\n const firestoreExp = container.getProvider('firestore').getImmediate()!;\n return firestoreFactory(app, firestoreExp);\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setServiceProps({ ...firestoreNamespace })\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport { FunctionsService } from './service';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactory\n} from '@firebase/component';\nimport { FUNCTIONS_TYPE } from './constants';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { MessagingInternalComponentName } from '@firebase/messaging-interop-types';\nimport { name, version } from '../package.json';\n\nconst AUTH_INTERNAL_NAME: FirebaseAuthInternalName = 'auth-internal';\nconst APP_CHECK_INTERNAL_NAME: AppCheckInternalComponentName =\n 'app-check-internal';\nconst MESSAGING_INTERNAL_NAME: MessagingInternalComponentName =\n 'messaging-internal';\n\nexport function registerFunctions(\n fetchImpl: typeof fetch,\n variant?: string\n): void {\n const factory: InstanceFactory<'functions'> = (\n container: ComponentContainer,\n { instanceIdentifier: regionOrCustomDomain }\n ) => {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider(AUTH_INTERNAL_NAME);\n const messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);\n const appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new FunctionsService(\n app,\n authProvider,\n messagingProvider,\n appCheckProvider,\n regionOrCustomDomain,\n fetchImpl\n );\n };\n\n _registerComponent(\n new Component(\n FUNCTIONS_TYPE,\n factory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '@firebase/firestore';\nimport { SetOptions } from '@firebase/firestore-types';\n\nexport function validateSetOptions(\n methodName: string,\n options: SetOptions | undefined\n): SetOptions {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n\n if (options.mergeFields !== undefined && options.merge !== undefined) {\n throw new FirestoreError(\n 'invalid-argument',\n `Invalid options passed to function ${methodName}(): You cannot ` +\n 'specify both \"merge\" and \"mergeFields\".'\n );\n }\n\n return options;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Bytes, FirestoreError, _isBase64Available } from '@firebase/firestore';\nimport { Compat } from '@firebase/util';\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable(): void {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(\n 'unimplemented',\n 'Uint8Arrays are not available in this environment.'\n );\n }\n}\n\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available(): void {\n if (!_isBase64Available()) {\n throw new FirestoreError(\n 'unimplemented',\n 'Blobs are unavailable in Firestore in this environment.'\n );\n }\n}\n\n/** Immutable class holding a blob (binary data) */\nexport class Blob implements Compat<Bytes> {\n constructor(readonly _delegate: Bytes) {}\n static fromBase64String(base64: string): Blob {\n assertBase64Available();\n return new Blob(Bytes.fromBase64String(base64));\n }\n\n static fromUint8Array(array: Uint8Array): Blob {\n assertUint8ArrayAvailable();\n return new Blob(Bytes.fromUint8Array(array));\n }\n\n toBase64(): string {\n assertBase64Available();\n return this._delegate.toBase64();\n }\n\n toUint8Array(): Uint8Array {\n assertUint8ArrayAvailable();\n return this._delegate.toUint8Array();\n }\n\n isEqual(other: Blob): boolean {\n return this._delegate.isEqual(other._delegate);\n }\n\n toString(): string {\n return 'Blob(base64: ' + this.toBase64() + ')';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '@firebase/firestore';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver<T> {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver<T>(obj: unknown): obj is PartialObserver<T> {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as Record<string, unknown>;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { _FirebaseApp, FirebaseService } from '@firebase/app-types/private';\nimport {\n LoadBundleTask,\n Bytes,\n clearIndexedDbPersistence,\n disableNetwork,\n enableIndexedDbPersistence,\n enableMultiTabIndexedDbPersistence,\n enableNetwork,\n ensureFirestoreConfigured,\n Firestore as ExpFirestore,\n connectFirestoreEmulator,\n waitForPendingWrites,\n FieldPath as ExpFieldPath,\n limit,\n limitToLast,\n where,\n orderBy,\n startAfter,\n startAt,\n query,\n endBefore,\n endAt,\n doc,\n collection,\n collectionGroup,\n queryEqual,\n Query as ExpQuery,\n CollectionReference as ExpCollectionReference,\n DocumentReference as ExpDocumentReference,\n refEqual,\n addDoc,\n deleteDoc,\n executeWrite,\n getDoc,\n getDocFromCache,\n getDocFromServer,\n getDocs,\n getDocsFromCache,\n getDocsFromServer,\n onSnapshot,\n onSnapshotsInSync,\n setDoc,\n updateDoc,\n Unsubscribe,\n DocumentChange as ExpDocumentChange,\n DocumentSnapshot as ExpDocumentSnapshot,\n QueryDocumentSnapshot as ExpQueryDocumentSnapshot,\n QuerySnapshot as ExpQuerySnapshot,\n snapshotEqual,\n SnapshotMetadata,\n runTransaction,\n Transaction as ExpTransaction,\n WriteBatch as ExpWriteBatch,\n AbstractUserDataWriter,\n FirestoreError,\n FirestoreDataConverter as ModularFirestoreDataConverter,\n setLogLevel as setClientLogLevel,\n _DatabaseId,\n _validateIsNotUsedTogether,\n _cast,\n _DocumentKey,\n _debugAssert,\n _FieldPath,\n _ResourcePath,\n _ByteString,\n _logWarn,\n namedQuery,\n loadBundle,\n PartialWithFieldValue,\n WithFieldValue\n} from '@firebase/firestore';\nimport {\n CollectionReference as PublicCollectionReference,\n DocumentChange as PublicDocumentChange,\n DocumentChangeType as PublicDocumentChangeType,\n DocumentData,\n DocumentData as PublicDocumentData,\n DocumentReference as PublicDocumentReference,\n DocumentSnapshot as PublicDocumentSnapshot,\n FieldPath as PublicFieldPath,\n FirebaseFirestore as PublicFirestore,\n FirestoreDataConverter as PublicFirestoreDataConverter,\n GetOptions as PublicGetOptions,\n LogLevel as PublicLogLevel,\n OrderByDirection as PublicOrderByDirection,\n PersistenceSettings as PublicPersistenceSettings,\n Query as PublicQuery,\n QueryDocumentSnapshot as PublicQueryDocumentSnapshot,\n QuerySnapshot as PublicQuerySnapshot,\n SetOptions as PublicSetOptions,\n Settings as PublicSettings,\n SnapshotListenOptions as PublicSnapshotListenOptions,\n SnapshotOptions as PublicSnapshotOptions,\n Transaction as PublicTransaction,\n UpdateData as PublicUpdateData,\n WhereFilterOp as PublicWhereFilterOp,\n WriteBatch as PublicWriteBatch\n} from '@firebase/firestore-types';\nimport {\n Compat,\n EmulatorMockTokenOptions,\n getModularInstance\n} from '@firebase/util';\n\nimport { validateSetOptions } from '../util/input_validation';\n\nimport { Blob } from './blob';\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from './observer';\n\n/**\n * A persistence provider for either memory-only or IndexedDB persistence.\n * Mainly used to allow optional inclusion of IndexedDB code.\n */\nexport interface PersistenceProvider {\n enableIndexedDbPersistence(\n firestore: Firestore,\n forceOwnership: boolean\n ): Promise<void>;\n enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;\n clearIndexedDbPersistence(firestore: Firestore): Promise<void>;\n}\n\n/**\n * The persistence provider included with the full Firestore SDK.\n */\nexport class IndexedDbPersistenceProvider implements PersistenceProvider {\n enableIndexedDbPersistence(\n firestore: Firestore,\n forceOwnership: boolean\n ): Promise<void> {\n return enableIndexedDbPersistence(firestore._delegate, { forceOwnership });\n }\n enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void> {\n return enableMultiTabIndexedDbPersistence(firestore._delegate);\n }\n clearIndexedDbPersistence(firestore: Firestore): Promise<void> {\n return clearIndexedDbPersistence(firestore._delegate);\n }\n}\n\n/**\n * Compat class for Firestore. Exposes Firestore Legacy API, but delegates\n * to the functional API of firestore-exp.\n */\nexport class Firestore\n implements PublicFirestore, FirebaseService, Compat<ExpFirestore>\n{\n _appCompat?: FirebaseApp;\n constructor(\n databaseIdOrApp: _DatabaseId | FirebaseApp,\n readonly _delegate: ExpFirestore,\n private _persistenceProvider: PersistenceProvider\n ) {\n if (!(databaseIdOrApp instanceof _DatabaseId)) {\n this._appCompat = databaseIdOrApp as FirebaseApp;\n }\n }\n\n get _databaseId(): _DatabaseId {\n return this._delegate._databaseId;\n }\n\n settings(settingsLiteral: PublicSettings): void {\n const currentSettings = this._delegate._getSettings();\n if (\n !settingsLiteral.merge &&\n currentSettings.host !== settingsLiteral.host\n ) {\n _logWarn(\n 'You are overriding the original host. If you did not intend ' +\n 'to override your settings, use {merge: true}.'\n );\n }\n\n if (settingsLiteral.merge) {\n settingsLiteral = {\n ...currentSettings,\n ...settingsLiteral\n };\n // Remove the property from the settings once the merge is completed\n delete settingsLiteral.merge;\n }\n\n this._delegate._setSettings(settingsLiteral);\n }\n\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n ): void {\n connectFirestoreEmulator(this._delegate, host, port, options);\n }\n\n enableNetwork(): Promise<void> {\n return enableNetwork(this._delegate);\n }\n\n disableNetwork(): Promise<void> {\n return disableNetwork(this._delegate);\n }\n\n enablePersistence(settings?: PublicPersistenceSettings): Promise<void> {\n let synchronizeTabs = false;\n let experimentalForceOwningTab = false;\n\n if (settings) {\n synchronizeTabs = !!settings.synchronizeTabs;\n experimentalForceOwningTab = !!settings.experimentalForceOwningTab;\n\n _validateIsNotUsedTogether(\n 'synchronizeTabs',\n synchronizeTabs,\n 'experimentalForceOwningTab',\n experimentalForceOwningTab\n );\n }\n\n return synchronizeTabs\n ? this._persistenceProvider.enableMultiTabIndexedDbPersistence(this)\n : this._persistenceProvider.enableIndexedDbPersistence(\n this,\n experimentalForceOwningTab\n );\n }\n\n clearPersistence(): Promise<void> {\n return this._persistenceProvider.clearIndexedDbPersistence(this);\n }\n\n terminate(): Promise<void> {\n if (this._appCompat) {\n (this._appCompat as _FirebaseApp)._removeServiceInstance(\n 'firestore-compat'\n );\n (this._appCompat as _FirebaseApp)._removeServiceInstance('firestore');\n }\n return this._delegate._delete();\n }\n\n waitForPendingWrites(): Promise<void> {\n return waitForPendingWrites(this._delegate);\n }\n\n onSnapshotsInSync(observer: PartialObserver<void>): Unsubscribe;\n onSnapshotsInSync(onSync: () => void): Unsubscribe;\n onSnapshotsInSync(arg: unknown): Unsubscribe {\n return onSnapshotsInSync(this._delegate, arg as PartialObserver<void>);\n }\n\n get app(): FirebaseApp {\n if (!this._appCompat) {\n throw new FirestoreError(\n 'failed-precondition',\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._appCompat as FirebaseApp;\n }\n\n INTERNAL = {\n delete: () => this.terminate()\n };\n\n collection(pathString: string): PublicCollectionReference {\n try {\n return new CollectionReference(\n this,\n collection(this._delegate, pathString)\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collection()',\n 'Firestore.collection()'\n );\n }\n }\n\n doc(pathString: string): PublicDocumentReference {\n try {\n return new DocumentReference(this, doc(this._delegate, pathString));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'doc()', 'Firestore.doc()');\n }\n }\n\n collectionGroup(collectionId: string): PublicQuery {\n try {\n return new Query(this, collectionGroup(this._delegate, collectionId));\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collectionGroup()',\n 'Firestore.collectionGroup()'\n );\n }\n }\n\n runTransaction<T>(\n updateFunction: (transaction: PublicTransaction) => Promise<T>\n ): Promise<T> {\n return runTransaction(this._delegate, transaction =>\n updateFunction(new Transaction(this, transaction))\n );\n }\n\n batch(): PublicWriteBatch {\n ensureFirestoreConfigured(this._delegate);\n return new WriteBatch(\n new ExpWriteBatch(this._delegate, mutations =>\n executeWrite(this._delegate, mutations)\n )\n );\n }\n\n loadBundle(\n bundleData: ArrayBuffer | ReadableStream<Uint8Array> | string\n ): LoadBundleTask {\n return loadBundle(this._delegate, bundleData);\n }\n\n namedQuery(name: string): Promise<PublicQuery<DocumentData> | null> {\n return namedQuery(this._delegate, name).then(expQuery => {\n if (!expQuery) {\n return null;\n }\n return new Query(\n this,\n // We can pass `expQuery` here directly since named queries don't have a UserDataConverter.\n // Otherwise, we would have to create a new ExpQuery and pass the old UserDataConverter.\n expQuery\n );\n });\n }\n}\n\nexport class UserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: _ByteString): Blob {\n return new Blob(new Bytes(bytes));\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return DocumentReference.forKey(key, this.firestore, /* converter= */ null);\n }\n}\n\nexport function setLogLevel(level: PublicLogLevel): void {\n setClientLogLevel(level);\n}\n\n/**\n * A reference to a transaction.\n */\nexport class Transaction implements PublicTransaction, Compat<ExpTransaction> {\n private _userDataWriter: UserDataWriter;\n\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpTransaction\n ) {\n this._userDataWriter = new UserDataWriter(_firestore);\n }\n\n get<T>(\n documentRef: PublicDocumentReference<T>\n ): Promise<PublicDocumentSnapshot<T>> {\n const ref = castReference(documentRef);\n return this._delegate\n .get(ref)\n .then(\n result =>\n new DocumentSnapshot(\n this._firestore,\n new ExpDocumentSnapshot<T>(\n this._firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n ref.converter\n )\n )\n );\n }\n\n set<T>(\n documentRef: DocumentReference<T>,\n data: Partial<T>,\n options: PublicSetOptions\n ): Transaction;\n set<T>(documentRef: DocumentReference<T>, data: T): Transaction;\n set<T>(\n documentRef: PublicDocumentReference<T>,\n data: T | Partial<T>,\n options?: PublicSetOptions\n ): Transaction {\n const ref = castReference(documentRef);\n if (options) {\n validateSetOptions('Transaction.set', options);\n this._delegate.set(ref, data as PartialWithFieldValue<T>, options);\n } else {\n this._delegate.set(ref, data as WithFieldValue<T>);\n }\n return this;\n }\n\n update(\n documentRef: PublicDocumentReference<unknown>,\n data: PublicUpdateData\n ): Transaction;\n update(\n documentRef: PublicDocumentReference<unknown>,\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction;\n update(\n documentRef: PublicDocumentReference<unknown>,\n dataOrField: unknown,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction {\n const ref = castReference(documentRef);\n if (arguments.length === 2) {\n this._delegate.update(ref, dataOrField as PublicUpdateData);\n } else {\n this._delegate.update(\n ref,\n dataOrField as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n\n return this;\n }\n\n delete(documentRef: PublicDocumentReference<unknown>): Transaction {\n const ref = castReference(documentRef);\n this._delegate.delete(ref);\n return this;\n }\n}\n\nexport class WriteBatch implements PublicWriteBatch, Compat<ExpWriteBatch> {\n constructor(readonly _delegate: ExpWriteBatch) {}\n set<T>(\n documentRef: DocumentReference<T>,\n data: Partial<T>,\n options: PublicSetOptions\n ): WriteBatch;\n set<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;\n set<T>(\n documentRef: PublicDocumentReference<T>,\n data: T | Partial<T>,\n options?: PublicSetOptions\n ): WriteBatch {\n const ref = castReference(documentRef);\n if (options) {\n validateSetOptions('WriteBatch.set', options);\n this._delegate.set(ref, data as PartialWithFieldValue<T>, options);\n } else {\n this._delegate.set(ref, data as WithFieldValue<T>);\n }\n return this;\n }\n\n update(\n documentRef: PublicDocumentReference<unknown>,\n data: PublicUpdateData\n ): WriteBatch;\n update(\n documentRef: PublicDocumentReference<unknown>,\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: PublicDocumentReference<unknown>,\n dataOrField: string | PublicFieldPath | PublicUpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n const ref = castReference(documentRef);\n if (arguments.length === 2) {\n this._delegate.update(ref, dataOrField as PublicUpdateData);\n } else {\n this._delegate.update(\n ref,\n dataOrField as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n return this;\n }\n\n delete(documentRef: PublicDocumentReference<unknown>): WriteBatch {\n const ref = castReference(documentRef);\n this._delegate.delete(ref);\n return this;\n }\n\n commit(): Promise<void> {\n return this._delegate.commit();\n }\n}\n\n/**\n * Wraps a `PublicFirestoreDataConverter` translating the types from the\n * experimental SDK into corresponding types from the Classic SDK before passing\n * them to the wrapped converter.\n */\nclass FirestoreDataConverter<U>\n implements\n ModularFirestoreDataConverter<U>,\n Compat<PublicFirestoreDataConverter<U>>\n{\n private static readonly INSTANCES = new WeakMap();\n\n private constructor(\n private readonly _firestore: Firestore,\n private readonly _userDataWriter: UserDataWriter,\n readonly _delegate: PublicFirestoreDataConverter<U>\n ) {}\n\n fromFirestore(\n snapshot: ExpQueryDocumentSnapshot,\n options?: PublicSnapshotOptions\n ): U {\n const expSnapshot = new ExpQueryDocumentSnapshot(\n this._firestore._delegate,\n this._userDataWriter,\n snapshot._key,\n snapshot._document,\n snapshot.metadata,\n /* converter= */ null\n );\n return this._delegate.fromFirestore(\n new QueryDocumentSnapshot(this._firestore, expSnapshot),\n options ?? {}\n );\n }\n\n toFirestore(modelObject: WithFieldValue<U>): PublicDocumentData;\n toFirestore(\n modelObject: PartialWithFieldValue<U>,\n options: PublicSetOptions\n ): PublicDocumentData;\n toFirestore(\n modelObject: WithFieldValue<U> | PartialWithFieldValue<U>,\n options?: PublicSetOptions\n ): PublicDocumentData {\n if (!options) {\n return this._delegate.toFirestore(modelObject as U);\n } else {\n return this._delegate.toFirestore(modelObject as Partial<U>, options);\n }\n }\n\n // Use the same instance of `FirestoreDataConverter` for the given instances\n // of `Firestore` and `PublicFirestoreDataConverter` so that isEqual() will\n // compare equal for two objects created with the same converter instance.\n static getInstance<U>(\n firestore: Firestore,\n converter: PublicFirestoreDataConverter<U>\n ): FirestoreDataConverter<U> {\n const converterMapByFirestore = FirestoreDataConverter.INSTANCES;\n let untypedConverterByConverter = converterMapByFirestore.get(firestore);\n if (!untypedConverterByConverter) {\n untypedConverterByConverter = new WeakMap();\n converterMapByFirestore.set(firestore, untypedConverterByConverter);\n }\n\n let instance = untypedConverterByConverter.get(converter);\n if (!instance) {\n instance = new FirestoreDataConverter(\n firestore,\n new UserDataWriter(firestore),\n converter\n );\n untypedConverterByConverter.set(converter, instance);\n }\n\n return instance;\n }\n}\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nexport class DocumentReference<T = PublicDocumentData>\n implements PublicDocumentReference<T>, Compat<ExpDocumentReference<T>>\n{\n private _userDataWriter: UserDataWriter;\n\n constructor(\n readonly firestore: Firestore,\n readonly _delegate: ExpDocumentReference<T>\n ) {\n this._userDataWriter = new UserDataWriter(firestore);\n }\n\n static forPath<U>(\n path: _ResourcePath,\n firestore: Firestore,\n converter: ModularFirestoreDataConverter<U> | null\n ): DocumentReference<U> {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(\n 'invalid-argument',\n 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n `${path.canonicalString()} has ${path.length}`\n );\n }\n return new DocumentReference(\n firestore,\n new ExpDocumentReference(\n firestore._delegate,\n converter,\n new _DocumentKey(path)\n )\n );\n }\n\n static forKey<U>(\n key: _DocumentKey,\n firestore: Firestore,\n converter: ModularFirestoreDataConverter<U> | null\n ): DocumentReference<U> {\n return new DocumentReference(\n firestore,\n new ExpDocumentReference(firestore._delegate, converter, key)\n );\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get parent(): PublicCollectionReference<T> {\n return new CollectionReference(this.firestore, this._delegate.parent);\n }\n\n get path(): string {\n return this._delegate.path;\n }\n\n collection(\n pathString: string\n ): PublicCollectionReference<PublicDocumentData> {\n try {\n return new CollectionReference(\n this.firestore,\n collection(this._delegate, pathString)\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collection()',\n 'DocumentReference.collection()'\n );\n }\n }\n\n isEqual(other: PublicDocumentReference<T>): boolean {\n other = getModularInstance<PublicDocumentReference<T>>(other);\n\n if (!(other instanceof ExpDocumentReference)) {\n return false;\n }\n return refEqual(this._delegate, other);\n }\n\n set(value: Partial<T>, options: PublicSetOptions): Promise<void>;\n set(value: T): Promise<void>;\n set(value: T | Partial<T>, options?: PublicSetOptions): Promise<void> {\n options = validateSetOptions('DocumentReference.set', options);\n try {\n if (options) {\n return setDoc(\n this._delegate,\n value as PartialWithFieldValue<T>,\n options\n );\n } else {\n return setDoc(this._delegate, value as WithFieldValue<T>);\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'setDoc()',\n 'DocumentReference.set()'\n );\n }\n }\n\n update(value: PublicUpdateData): Promise<void>;\n update(\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void>;\n update(\n fieldOrUpdateData: string | PublicFieldPath | PublicUpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void> {\n try {\n if (arguments.length === 1) {\n return updateDoc(this._delegate, fieldOrUpdateData as PublicUpdateData);\n } else {\n return updateDoc(\n this._delegate,\n fieldOrUpdateData as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'updateDoc()',\n 'DocumentReference.update()'\n );\n }\n }\n\n delete(): Promise<void> {\n return deleteDoc(this._delegate);\n }\n\n onSnapshot(observer: PartialObserver<PublicDocumentSnapshot<T>>): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n observer: PartialObserver<PublicDocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<PublicDocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n onNext: NextFn<PublicDocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n const options = extractSnapshotOptions(args);\n const observer = wrapObserver<DocumentSnapshot<T>, ExpDocumentSnapshot<T>>(\n args,\n result =>\n new DocumentSnapshot(\n this.firestore,\n new ExpDocumentSnapshot(\n this.firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n this._delegate.converter\n )\n )\n );\n return onSnapshot(this._delegate, options, observer);\n }\n\n get(options?: PublicGetOptions): Promise<PublicDocumentSnapshot<T>> {\n let snap: Promise<ExpDocumentSnapshot<T>>;\n if (options?.source === 'cache') {\n snap = getDocFromCache(this._delegate);\n } else if (options?.source === 'server') {\n snap = getDocFromServer(this._delegate);\n } else {\n snap = getDoc(this._delegate);\n }\n\n return snap.then(\n result =>\n new DocumentSnapshot(\n this.firestore,\n new ExpDocumentSnapshot(\n this.firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n this._delegate.converter\n )\n )\n );\n }\n\n withConverter(converter: null): PublicDocumentReference<PublicDocumentData>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U>\n ): PublicDocumentReference<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): PublicDocumentReference<U> {\n return new DocumentReference<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpDocumentReference<U>)\n );\n }\n}\n\n/**\n * Replaces the function name in an error thrown by the firestore-exp API\n * with the function names used in the classic API.\n */\nfunction replaceFunctionName(\n e: Error,\n original: string | RegExp,\n updated: string\n): Error {\n e.message = e.message.replace(original, updated);\n return e;\n}\n\n/**\n * Iterates the list of arguments from an `onSnapshot` call and returns the\n * first argument that may be an `SnapshotListenOptions` object. Returns an\n * empty object if none is found.\n */\nexport function extractSnapshotOptions(\n args: unknown[]\n): PublicSnapshotListenOptions {\n for (const arg of args) {\n if (typeof arg === 'object' && !isPartialObserver(arg)) {\n return arg as PublicSnapshotListenOptions;\n }\n }\n return {};\n}\n\n/**\n * Creates an observer that can be passed to the firestore-exp SDK. The\n * observer converts all observed values into the format expected by the classic\n * SDK.\n *\n * @param args - The list of arguments from an `onSnapshot` call.\n * @param wrapper - The function that converts the firestore-exp type into the\n * type used by this shim.\n */\nexport function wrapObserver<CompatType, ExpType>(\n args: unknown[],\n wrapper: (val: ExpType) => CompatType\n): PartialObserver<ExpType> {\n let userObserver: PartialObserver<CompatType>;\n if (isPartialObserver(args[0])) {\n userObserver = args[0] as PartialObserver<CompatType>;\n } else if (isPartialObserver(args[1])) {\n userObserver = args[1];\n } else if (typeof args[0] === 'function') {\n userObserver = {\n next: args[0] as NextFn<CompatType> | undefined,\n error: args[1] as ErrorFn | undefined,\n complete: args[2] as CompleteFn | undefined\n };\n } else {\n userObserver = {\n next: args[1] as NextFn<CompatType> | undefined,\n error: args[2] as ErrorFn | undefined,\n complete: args[3] as CompleteFn | undefined\n };\n }\n\n return {\n next: val => {\n if (userObserver!.next) {\n userObserver!.next(wrapper(val));\n }\n },\n error: userObserver.error?.bind(userObserver),\n complete: userObserver.complete?.bind(userObserver)\n };\n}\n\n/**\n * Options interface that can be provided to configure the deserialization of\n * DocumentSnapshots.\n */\nexport interface SnapshotOptions extends PublicSnapshotOptions {}\n\nexport class DocumentSnapshot<T = PublicDocumentData>\n implements PublicDocumentSnapshot<T>, Compat<ExpDocumentSnapshot<T>>\n{\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpDocumentSnapshot<T>\n ) {}\n\n get ref(): DocumentReference<T> {\n return new DocumentReference<T>(this._firestore, this._delegate.ref);\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get metadata(): SnapshotMetadata {\n return this._delegate.metadata;\n }\n\n get exists(): boolean {\n return this._delegate.exists();\n }\n\n data(options?: PublicSnapshotOptions): T | undefined {\n return this._delegate.data(options);\n }\n\n get(\n fieldPath: string | PublicFieldPath,\n options?: PublicSnapshotOptions\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n return this._delegate.get(fieldPath as string | ExpFieldPath, options);\n }\n\n isEqual(other: DocumentSnapshot<T>): boolean {\n return snapshotEqual(this._delegate, other._delegate);\n }\n}\n\nexport class QueryDocumentSnapshot<T = PublicDocumentData>\n extends DocumentSnapshot<T>\n implements PublicQueryDocumentSnapshot<T>\n{\n data(options?: PublicSnapshotOptions): T {\n const data = this._delegate.data(options);\n _debugAssert(\n data !== undefined,\n 'Document in a QueryDocumentSnapshot should exist'\n );\n return data;\n }\n}\n\nexport class Query<T = PublicDocumentData>\n implements PublicQuery<T>, Compat<ExpQuery<T>>\n{\n private readonly _userDataWriter: UserDataWriter;\n\n constructor(readonly firestore: Firestore, readonly _delegate: ExpQuery<T>) {\n this._userDataWriter = new UserDataWriter(firestore);\n }\n\n where(\n fieldPath: string | _FieldPath,\n opStr: PublicWhereFilterOp,\n value: unknown\n ): Query<T> {\n try {\n // The \"as string\" cast is a little bit of a hack. `where` accepts the\n // FieldPath Compat type as input, but is not typed as such in order to\n // not expose this via our public typings file.\n return new Query<T>(\n this.firestore,\n query(this._delegate, where(fieldPath as string, opStr, value))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n /(orderBy|where)\\(\\)/,\n 'Query.$1()'\n );\n }\n }\n\n orderBy(\n fieldPath: string | _FieldPath,\n directionStr?: PublicOrderByDirection\n ): Query<T> {\n try {\n // The \"as string\" cast is a little bit of a hack. `orderBy` accepts the\n // FieldPath Compat type as input, but is not typed as such in order to\n // not expose this via our public typings file.\n return new Query<T>(\n this.firestore,\n query(this._delegate, orderBy(fieldPath as string, directionStr))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n /(orderBy|where)\\(\\)/,\n 'Query.$1()'\n );\n }\n }\n\n limit(n: number): Query<T> {\n try {\n return new Query<T>(this.firestore, query(this._delegate, limit(n)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'limit()', 'Query.limit()');\n }\n }\n\n limitToLast(n: number): Query<T> {\n try {\n return new Query<T>(\n this.firestore,\n query(this._delegate, limitToLast(n))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'limitToLast()',\n 'Query.limitToLast()'\n );\n }\n }\n\n startAt(...args: any[]): Query<T> {\n try {\n return new Query(this.firestore, query(this._delegate, startAt(...args)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'startAt()', 'Query.startAt()');\n }\n }\n\n startAfter(...args: any[]): Query<T> {\n try {\n return new Query(\n this.firestore,\n query(this._delegate, startAfter(...args))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'startAfter()',\n 'Query.startAfter()'\n );\n }\n }\n\n endBefore(...args: any[]): Query<T> {\n try {\n return new Query(\n this.firestore,\n query(this._delegate, endBefore(...args))\n );\n } catch (e) {\n throw replaceFunctionName(e as Error, 'endBefore()', 'Query.endBefore()');\n }\n }\n\n endAt(...args: any[]): Query<T> {\n try {\n return new Query(this.firestore, query(this._delegate, endAt(...args)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'endAt()', 'Query.endAt()');\n }\n }\n\n isEqual(other: PublicQuery<T>): boolean {\n return queryEqual(this._delegate, (other as Query<T>)._delegate);\n }\n\n get(options?: PublicGetOptions): Promise<QuerySnapshot<T>> {\n let query: Promise<ExpQuerySnapshot<T>>;\n if (options?.source === 'cache') {\n query = getDocsFromCache(this._delegate);\n } else if (options?.source === 'server') {\n query = getDocsFromServer(this._delegate);\n } else {\n query = getDocs(this._delegate);\n }\n return query.then(\n result =>\n new QuerySnapshot(\n this.firestore,\n new ExpQuerySnapshot<T>(\n this.firestore._delegate,\n this._userDataWriter,\n this._delegate,\n result._snapshot\n )\n )\n );\n }\n\n onSnapshot(observer: PartialObserver<PublicQuerySnapshot<T>>): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n observer: PartialObserver<PublicQuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<PublicQuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n onNext: NextFn<PublicQuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n const options = extractSnapshotOptions(args);\n const observer = wrapObserver<QuerySnapshot<T>, ExpQuerySnapshot<T>>(\n args,\n snap =>\n new QuerySnapshot(\n this.firestore,\n new ExpQuerySnapshot<T>(\n this.firestore._delegate,\n this._userDataWriter,\n this._delegate,\n snap._snapshot\n )\n )\n );\n return onSnapshot(this._delegate, options, observer);\n }\n\n withConverter(converter: null): Query<PublicDocumentData>;\n withConverter<U>(converter: PublicFirestoreDataConverter<U>): Query<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): Query<U> {\n return new Query<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpQuery<U>)\n );\n }\n}\n\nexport class DocumentChange<T = PublicDocumentData>\n implements PublicDocumentChange<T>, Compat<ExpDocumentChange<T>>\n{\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpDocumentChange<T>\n ) {}\n\n get type(): PublicDocumentChangeType {\n return this._delegate.type;\n }\n\n get doc(): QueryDocumentSnapshot<T> {\n return new QueryDocumentSnapshot<T>(this._firestore, this._delegate.doc);\n }\n\n get oldIndex(): number {\n return this._delegate.oldIndex;\n }\n\n get newIndex(): number {\n return this._delegate.newIndex;\n }\n}\n\nexport class QuerySnapshot<T = PublicDocumentData>\n implements PublicQuerySnapshot<T>, Compat<ExpQuerySnapshot<T>>\n{\n constructor(\n readonly _firestore: Firestore,\n readonly _delegate: ExpQuerySnapshot<T>\n ) {}\n\n get query(): Query<T> {\n return new Query(this._firestore, this._delegate.query);\n }\n\n get metadata(): SnapshotMetadata {\n return this._delegate.metadata;\n }\n\n get size(): number {\n return this._delegate.size;\n }\n\n get empty(): boolean {\n return this._delegate.empty;\n }\n\n get docs(): Array<QueryDocumentSnapshot<T>> {\n return this._delegate.docs.map(\n doc => new QueryDocumentSnapshot<T>(this._firestore, doc)\n );\n }\n\n docChanges(\n options?: PublicSnapshotListenOptions\n ): Array<PublicDocumentChange<T>> {\n return this._delegate\n .docChanges(options)\n .map(docChange => new DocumentChange<T>(this._firestore, docChange));\n }\n\n forEach(\n callback: (result: QueryDocumentSnapshot<T>) => void,\n thisArg?: unknown\n ): void {\n this._delegate.forEach(snapshot => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot(this._firestore, snapshot)\n );\n });\n }\n\n isEqual(other: QuerySnapshot<T>): boolean {\n return snapshotEqual(this._delegate, other._delegate);\n }\n}\n\nexport class CollectionReference<T = PublicDocumentData>\n extends Query<T>\n implements PublicCollectionReference<T>\n{\n constructor(\n readonly firestore: Firestore,\n readonly _delegate: ExpCollectionReference<T>\n ) {\n super(firestore, _delegate);\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get path(): string {\n return this._delegate.path;\n }\n\n get parent(): DocumentReference<PublicDocumentData> | null {\n const docRef = this._delegate.parent;\n return docRef ? new DocumentReference(this.firestore, docRef) : null;\n }\n\n doc(documentPath?: string): DocumentReference<T> {\n try {\n if (documentPath === undefined) {\n // Call `doc` without `documentPath` if `documentPath` is `undefined`\n // as `doc` validates the number of arguments to prevent users from\n // accidentally passing `undefined`.\n return new DocumentReference(this.firestore, doc(this._delegate));\n } else {\n return new DocumentReference(\n this.firestore,\n doc(this._delegate, documentPath)\n );\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'doc()',\n 'CollectionReference.doc()'\n );\n }\n }\n\n add(data: T): Promise<DocumentReference<T>> {\n return addDoc(this._delegate, data as WithFieldValue<T>).then(\n docRef => new DocumentReference(this.firestore, docRef)\n );\n }\n\n isEqual(other: CollectionReference<T>): boolean {\n return refEqual(this._delegate, other._delegate);\n }\n\n withConverter(converter: null): CollectionReference<PublicDocumentData>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U>\n ): CollectionReference<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): CollectionReference<U> {\n return new CollectionReference<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpCollectionReference<U>)\n );\n }\n}\n\nfunction castReference<T>(\n documentRef: PublicDocumentReference<T>\n): ExpDocumentReference<T> {\n return _cast<ExpDocumentReference<T>>(documentRef, ExpDocumentReference);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FieldPath as ExpFieldPath,\n _FieldPath as InternalFieldPath\n} from '@firebase/firestore';\nimport { FieldPath as PublicFieldPath } from '@firebase/firestore-types';\nimport { Compat, getModularInstance } from '@firebase/util';\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a list\n * of field names (referring to a nested field in the document).\n */\nexport class FieldPath implements PublicFieldPath, Compat<ExpFieldPath> {\n readonly _delegate: ExpFieldPath;\n /**\n * Creates a FieldPath from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n this._delegate = new ExpFieldPath(...fieldNames);\n }\n\n static documentId(): FieldPath {\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n return new FieldPath(InternalFieldPath.keyField().canonicalString());\n }\n\n isEqual(other: PublicFieldPath): boolean {\n other = getModularInstance(other);\n\n if (!(other instanceof ExpFieldPath)) {\n return false;\n }\n return this._delegate._internalPath.isEqual(other._internalPath);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n arrayRemove,\n arrayUnion,\n deleteField,\n FieldValue as FieldValue1,\n increment,\n serverTimestamp\n} from '@firebase/firestore';\nimport { FieldValue as PublicFieldValue } from '@firebase/firestore-types';\nimport { Compat } from '@firebase/util';\n\nexport class FieldValue implements PublicFieldValue, Compat<FieldValue1> {\n static serverTimestamp(): FieldValue {\n const delegate = serverTimestamp();\n delegate._methodName = 'FieldValue.serverTimestamp';\n return new FieldValue(delegate);\n }\n\n static delete(): FieldValue {\n const delegate = deleteField();\n delegate._methodName = 'FieldValue.delete';\n return new FieldValue(delegate);\n }\n\n static arrayUnion(...elements: unknown[]): FieldValue {\n const delegate = arrayUnion(...elements);\n delegate._methodName = 'FieldValue.arrayUnion';\n return new FieldValue(delegate);\n }\n\n static arrayRemove(...elements: unknown[]): FieldValue {\n const delegate = arrayRemove(...elements);\n delegate._methodName = 'FieldValue.arrayRemove';\n return new FieldValue(delegate);\n }\n\n static increment(n: number): FieldValue {\n const delegate = increment(n);\n delegate._methodName = 'FieldValue.increment';\n return new FieldValue(delegate);\n }\n\n constructor(readonly _delegate: FieldValue1) {}\n\n isEqual(other: FieldValue): boolean {\n return this._delegate.isEqual(other._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\nconst UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\n\nfunction mapValues(\n // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n o: { [key: string]: any },\n f: (arg0: unknown) => unknown\n): object {\n const result: { [key: string]: unknown } = {};\n for (const key in o) {\n if (o.hasOwnProperty(key)) {\n result[key] = f(o[key]);\n }\n }\n return result;\n}\n\n/**\n * Takes data and encodes it in a JSON-friendly way, such that types such as\n * Date are preserved.\n * @internal\n * @param data - Data to encode.\n */\nexport function encode(data: unknown): unknown {\n if (data == null) {\n return null;\n }\n if (data instanceof Number) {\n data = data.valueOf();\n }\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n if (data === true || data === false) {\n return data;\n }\n if (Object.prototype.toString.call(data) === '[object String]') {\n return data;\n }\n if (data instanceof Date) {\n return data.toISOString();\n }\n if (Array.isArray(data)) {\n return data.map(x => encode(x));\n }\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data!, x => encode(x));\n }\n // If we got this far, the data is not encodable.\n throw new Error('Data cannot be encoded in JSON: ' + data);\n}\n\n/**\n * Takes data that's been encoded in a JSON-friendly form and returns a form\n * with richer datatypes, such as Dates, etc.\n * @internal\n * @param json - JSON to convert.\n */\nexport function decode(json: unknown): unknown {\n if (json == null) {\n return json;\n }\n if ((json as { [key: string]: unknown })['@type']) {\n switch ((json as { [key: string]: unknown })['@type']) {\n case LONG_TYPE:\n // Fall through and handle this the same as unsigned.\n case UNSIGNED_LONG_TYPE: {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n const value = Number((json as { [key: string]: unknown })['value']);\n if (isNaN(value)) {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n return value;\n }\n default: {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n }\n }\n if (Array.isArray(json)) {\n return json.map(x => decode(x));\n }\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json!, x => decode(x));\n }\n // Anything else is safe to return.\n return json;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Functions.\n */\nexport const FUNCTIONS_TYPE = 'functions';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FunctionsErrorCodeCore as FunctionsErrorCode } from './public-types';\nimport { decode } from './serializer';\nimport { HttpResponseBody } from './service';\nimport { FirebaseError } from '@firebase/util';\nimport { FUNCTIONS_TYPE } from './constants';\n\n/**\n * Standard error codes for different ways a request can fail, as defined by:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * This map is used primarily to convert from a backend error code string to\n * a client SDK error code string, and make sure it's in the supported set.\n */\nconst errorCodeMap: { [name: string]: FunctionsErrorCode } = {\n OK: 'ok',\n CANCELLED: 'cancelled',\n UNKNOWN: 'unknown',\n INVALID_ARGUMENT: 'invalid-argument',\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n NOT_FOUND: 'not-found',\n ALREADY_EXISTS: 'already-exists',\n PERMISSION_DENIED: 'permission-denied',\n UNAUTHENTICATED: 'unauthenticated',\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n FAILED_PRECONDITION: 'failed-precondition',\n ABORTED: 'aborted',\n OUT_OF_RANGE: 'out-of-range',\n UNIMPLEMENTED: 'unimplemented',\n INTERNAL: 'internal',\n UNAVAILABLE: 'unavailable',\n DATA_LOSS: 'data-loss'\n};\n\n/**\n * An explicit error that can be thrown from a handler to send an error to the\n * client that called the function.\n */\nexport class FunctionsError extends FirebaseError {\n constructor(\n /**\n * A standard error code that will be returned to the client. This also\n * determines the HTTP status code of the response, as defined in code.proto.\n */\n code: FunctionsErrorCode,\n message?: string,\n /**\n * Extra data to be converted to JSON and included in the error response.\n */\n readonly details?: unknown\n ) {\n super(`${FUNCTIONS_TYPE}/${code}`, message || '');\n }\n}\n\n/**\n * Takes an HTTP status code and returns the corresponding ErrorCode.\n * This is the standard HTTP status code -> error mapping defined in:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * @param status An HTTP status code.\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\n */\nfunction codeForHTTPStatus(status: number): FunctionsErrorCode {\n // Make sure any successful status is OK.\n if (status >= 200 && status < 300) {\n return 'ok';\n }\n switch (status) {\n case 0:\n // This can happen if the server returns 500.\n return 'internal';\n case 400:\n return 'invalid-argument';\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission-denied';\n case 404:\n return 'not-found';\n case 409:\n return 'aborted';\n case 429:\n return 'resource-exhausted';\n case 499:\n return 'cancelled';\n case 500:\n return 'internal';\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline-exceeded';\n default: // ignore\n }\n return 'unknown';\n}\n\n/**\n * Takes an HTTP response and returns the corresponding Error, if any.\n */\nexport function _errorForResponse(\n status: number,\n bodyJSON: HttpResponseBody | null\n): Error | null {\n let code = codeForHTTPStatus(status);\n\n // Start with reasonable defaults from the status code.\n let description: string = code;\n\n let details: unknown = undefined;\n\n // Then look through the body for explicit details.\n try {\n const errorJSON = bodyJSON && bodyJSON.error;\n if (errorJSON) {\n const status = errorJSON.status;\n if (typeof status === 'string') {\n if (!errorCodeMap[status]) {\n // They must've included an unknown error code in the body.\n return new FunctionsError('internal', 'internal');\n }\n code = errorCodeMap[status];\n\n // TODO(klimt): Add better default descriptions for error enums.\n // The default description needs to be updated for the new code.\n description = status;\n }\n\n const message = errorJSON.message;\n if (typeof message === 'string') {\n description = message;\n }\n\n details = errorJSON.details;\n if (details !== undefined) {\n details = decode(details);\n }\n }\n } catch (e) {\n // If we couldn't parse explicit error data, that's fine.\n }\n\n if (code === 'ok') {\n // Technically, there's an edge case where a developer could explicitly\n // return an error code of OK, and we will treat it as success, but that\n // seems reasonable.\n return null;\n }\n\n return new FunctionsError(code, description, details);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from '@firebase/component';\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n MessagingInternal,\n MessagingInternalComponentName\n} from '@firebase/messaging-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\n\n/**\n * The metadata that should be supplied with function calls.\n * @internal\n */\nexport interface Context {\n authToken?: string;\n messagingToken?: string;\n appCheckToken: string | null;\n}\n\n/**\n * Helper class to get metadata that should be included with a function call.\n * @internal\n */\nexport class ContextProvider {\n private auth: FirebaseAuthInternal | null = null;\n private messaging: MessagingInternal | null = null;\n private appCheck: FirebaseAppCheckInternal | null = null;\n constructor(\n authProvider: Provider<FirebaseAuthInternalName>,\n messagingProvider: Provider<MessagingInternalComponentName>,\n appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {\n this.auth = authProvider.getImmediate({ optional: true });\n this.messaging = messagingProvider.getImmediate({\n optional: true\n });\n\n if (!this.auth) {\n authProvider.get().then(\n auth => (this.auth = auth),\n () => {\n /* get() never rejects */\n }\n );\n }\n\n if (!this.messaging) {\n messagingProvider.get().then(\n messaging => (this.messaging = messaging),\n () => {\n /* get() never rejects */\n }\n );\n }\n\n if (!this.appCheck) {\n appCheckProvider.get().then(\n appCheck => (this.appCheck = appCheck),\n () => {\n /* get() never rejects */\n }\n );\n }\n }\n\n async getAuthToken(): Promise<string | undefined> {\n if (!this.auth) {\n return undefined;\n }\n\n try {\n const token = await this.auth.getToken();\n return token?.accessToken;\n } catch (e) {\n // If there's any error when trying to get the auth token, leave it off.\n return undefined;\n }\n }\n\n async getMessagingToken(): Promise<string | undefined> {\n if (\n !this.messaging ||\n !('Notification' in self) ||\n Notification.permission !== 'granted'\n ) {\n return undefined;\n }\n\n try {\n return await this.messaging.getToken();\n } catch (e) {\n // We don't warn on this, because it usually means messaging isn't set up.\n // console.warn('Failed to retrieve instance id token.', e);\n\n // If there's any error when trying to get the token, leave it off.\n return undefined;\n }\n }\n\n async getAppCheckToken(): Promise<string | null> {\n if (this.appCheck) {\n const result = await this.appCheck.getToken();\n if (result.error) {\n // Do not send the App Check header to the functions endpoint if\n // there was an error from the App Check exchange endpoint. The App\n // Check SDK will already have logged the error to console.\n return null;\n }\n return result.token;\n }\n return null;\n }\n\n async getContext(): Promise<Context> {\n const authToken = await this.getAuthToken();\n const messagingToken = await this.getMessagingToken();\n const appCheckToken = await this.getAppCheckToken();\n return { authToken, messagingToken, appCheckToken };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport {\n HttpsCallable,\n HttpsCallableResult,\n HttpsCallableOptions\n} from './public-types';\nimport { _errorForResponse, FunctionsError } from './error';\nimport { ContextProvider } from './context';\nimport { encode, decode } from './serializer';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { MessagingInternalComponentName } from '@firebase/messaging-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\n\nexport const DEFAULT_REGION = 'us-central1';\n\n/**\n * The response to an http request.\n */\ninterface HttpResponse {\n status: number;\n json: HttpResponseBody | null;\n}\n/**\n * Describes the shape of the HttpResponse body.\n * It makes functions that would otherwise take {} able to access the\n * possible elements in the body more easily\n */\nexport interface HttpResponseBody {\n data?: unknown;\n result?: unknown;\n error?: {\n message?: unknown;\n status?: unknown;\n details?: unknown;\n };\n}\n\ninterface CancellablePromise<T> {\n promise: Promise<T>;\n cancel: () => void;\n}\n\n/**\n * Returns a Promise that will be rejected after the given duration.\n * The error will be of type FunctionsError.\n *\n * @param millis Number of milliseconds to wait before rejecting.\n */\nfunction failAfter(millis: number): CancellablePromise<never> {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let timer: any | null = null;\n return {\n promise: new Promise((_, reject) => {\n timer = setTimeout(() => {\n reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));\n }, millis);\n }),\n cancel: () => {\n if (timer) {\n clearTimeout(timer);\n }\n }\n };\n}\n\n/**\n * The main class for the Firebase Functions SDK.\n * @internal\n */\nexport class FunctionsService implements _FirebaseService {\n readonly contextProvider: ContextProvider;\n emulatorOrigin: string | null = null;\n cancelAllRequests: Promise<void>;\n deleteService!: () => Promise<void>;\n region: string;\n customDomain: string | null;\n\n /**\n * Creates a new Functions service for the given app.\n * @param app - The FirebaseApp to use.\n */\n constructor(\n readonly app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n messagingProvider: Provider<MessagingInternalComponentName>,\n appCheckProvider: Provider<AppCheckInternalComponentName>,\n regionOrCustomDomain: string = DEFAULT_REGION,\n readonly fetchImpl: typeof fetch\n ) {\n this.contextProvider = new ContextProvider(\n authProvider,\n messagingProvider,\n appCheckProvider\n );\n // Cancels all ongoing requests when resolved.\n this.cancelAllRequests = new Promise(resolve => {\n this.deleteService = () => {\n return Promise.resolve(resolve());\n };\n });\n\n // Resolve the region or custom domain overload by attempting to parse it.\n try {\n const url = new URL(regionOrCustomDomain);\n this.customDomain = url.origin;\n this.region = DEFAULT_REGION;\n } catch (e) {\n this.customDomain = null;\n this.region = regionOrCustomDomain;\n }\n }\n\n _delete(): Promise<void> {\n return this.deleteService();\n }\n\n /**\n * Returns the URL for a callable with the given name.\n * @param name - The name of the callable.\n * @internal\n */\n _url(name: string): string {\n const projectId = this.app.options.projectId;\n if (this.emulatorOrigin !== null) {\n const origin = this.emulatorOrigin;\n return `${origin}/${projectId}/${this.region}/${name}`;\n }\n\n if (this.customDomain !== null) {\n return `${this.customDomain}/${name}`;\n }\n\n return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`;\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Functions emulator.\n *\n * Note: this must be called before this instance has been used to do any operations.\n *\n * @param host The emulator host (ex: localhost)\n * @param port The emulator port (ex: 5001)\n * @public\n */\nexport function connectFunctionsEmulator(\n functionsInstance: FunctionsService,\n host: string,\n port: number\n): void {\n functionsInstance.emulatorOrigin = `http://${host}:${port}`;\n}\n\n/**\n * Returns a reference to the callable https trigger with the given name.\n * @param name - The name of the trigger.\n * @public\n */\nexport function httpsCallable<RequestData, ResponseData>(\n functionsInstance: FunctionsService,\n name: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return (data => {\n return call(functionsInstance, name, data, options || {});\n }) as HttpsCallable<RequestData, ResponseData>;\n}\n\n/**\n * Returns a reference to the callable https trigger with the given url.\n * @param url - The url of the trigger.\n * @public\n */\nexport function httpsCallableFromURL<RequestData, ResponseData>(\n functionsInstance: FunctionsService,\n url: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return (data => {\n return callAtURL(functionsInstance, url, data, options || {});\n }) as HttpsCallable<RequestData, ResponseData>;\n}\n\n/**\n * Does an HTTP POST and returns the completed response.\n * @param url The url to post to.\n * @param body The JSON body of the post.\n * @param headers The HTTP headers to include in the request.\n * @return A Promise that will succeed when the request finishes.\n */\nasync function postJSON(\n url: string,\n body: unknown,\n headers: { [key: string]: string },\n fetchImpl: typeof fetch\n): Promise<HttpResponse> {\n headers['Content-Type'] = 'application/json';\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers\n });\n } catch (e) {\n // This could be an unhandled error on the backend, or it could be a\n // network error. There's no way to know, since an unhandled error on the\n // backend will fail to set the proper CORS header, and thus will be\n // treated as a network error by fetch.\n return {\n status: 0,\n json: null\n };\n }\n let json: HttpResponseBody | null = null;\n try {\n json = await response.json();\n } catch (e) {\n // If we fail to parse JSON, it will fail the same as an empty body.\n }\n return {\n status: response.status,\n json\n };\n}\n\n/**\n * Calls a callable function asynchronously and returns the result.\n * @param name The name of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\nfunction call(\n functionsInstance: FunctionsService,\n name: string,\n data: unknown,\n options: HttpsCallableOptions\n): Promise<HttpsCallableResult> {\n const url = functionsInstance._url(name);\n return callAtURL(functionsInstance, url, data, options);\n}\n\n/**\n * Calls a callable function asynchronously and returns the result.\n * @param url The url of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\nasync function callAtURL(\n functionsInstance: FunctionsService,\n url: string,\n data: unknown,\n options: HttpsCallableOptions\n): Promise<HttpsCallableResult> {\n // Encode any special types, such as dates, in the input data.\n data = encode(data);\n const body = { data };\n\n // Add a header for the authToken.\n const headers: { [key: string]: string } = {};\n const context = await functionsInstance.contextProvider.getContext();\n if (context.authToken) {\n headers['Authorization'] = 'Bearer ' + context.authToken;\n }\n if (context.messagingToken) {\n headers['Firebase-Instance-ID-Token'] = context.messagingToken;\n }\n if (context.appCheckToken !== null) {\n headers['X-Firebase-AppCheck'] = context.appCheckToken;\n }\n\n // Default timeout to 70s, but let the options override it.\n const timeout = options.timeout || 70000;\n\n const failAfterHandle = failAfter(timeout);\n const response = await Promise.race([\n postJSON(url, body, headers, functionsInstance.fetchImpl),\n failAfterHandle.promise,\n functionsInstance.cancelAllRequests\n ]);\n\n // Always clear the failAfter timeout\n failAfterHandle.cancel();\n\n // If service was deleted, interrupted response throws an error.\n if (!response) {\n throw new FunctionsError(\n 'cancelled',\n 'Firebase Functions instance was deleted.'\n );\n }\n\n // Check for an error status, regardless of http status.\n const error = _errorForResponse(response.status, response.json);\n if (error) {\n throw error;\n }\n\n if (!response.json) {\n throw new FunctionsError('internal', 'Response is not valid JSON object.');\n }\n\n let responseData = response.json.data;\n // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\n // backwards compatibility.\n if (typeof responseData === 'undefined') {\n responseData = response.json.result;\n }\n if (typeof responseData === 'undefined') {\n // Consider the response malformed.\n throw new FunctionsError('internal', 'Response is missing data field.');\n }\n\n // Decode any special types, such as dates, in the returned data.\n const decodedData = decode(responseData);\n\n return { data: decodedData };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport { FUNCTIONS_TYPE } from './constants';\n\nimport { Provider } from '@firebase/component';\nimport { Functions, HttpsCallableOptions, HttpsCallable } from './public-types';\nimport {\n FunctionsService,\n DEFAULT_REGION,\n connectFunctionsEmulator as _connectFunctionsEmulator,\n httpsCallable as _httpsCallable,\n httpsCallableFromURL as _httpsCallableFromURL\n} from './service';\nimport {\n getModularInstance,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nexport * from './public-types';\n\n/**\n * Returns a {@link Functions} instance for the given app.\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n * @param regionOrCustomDomain - one of:\n * a) The region the callable functions are located in (ex: us-central1)\n * b) A custom domain hosting the callable functions (ex: https://mydomain.com)\n * @public\n */\nexport function getFunctions(\n app: FirebaseApp = getApp(),\n regionOrCustomDomain: string = DEFAULT_REGION\n): Functions {\n // Dependencies\n const functionsProvider: Provider<'functions'> = _getProvider(\n getModularInstance(app),\n FUNCTIONS_TYPE\n );\n const functionsInstance = functionsProvider.getImmediate({\n identifier: regionOrCustomDomain\n });\n const emulator = getDefaultEmulatorHostnameAndPort('functions');\n if (emulator) {\n connectFunctionsEmulator(functionsInstance, ...emulator);\n }\n return functionsInstance;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Functions emulator.\n *\n * Note: this must be called before this instance has been used to do any operations.\n *\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 5001)\n * @public\n */\nexport function connectFunctionsEmulator(\n functionsInstance: Functions,\n host: string,\n port: number\n): void {\n _connectFunctionsEmulator(\n getModularInstance<FunctionsService>(functionsInstance as FunctionsService),\n host,\n port\n );\n}\n\n/**\n * Returns a reference to the callable HTTPS trigger with the given name.\n * @param name - The name of the trigger.\n * @public\n */\nexport function httpsCallable<RequestData = unknown, ResponseData = unknown>(\n functionsInstance: Functions,\n name: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return _httpsCallable<RequestData, ResponseData>(\n getModularInstance<FunctionsService>(functionsInstance as FunctionsService),\n name,\n options\n );\n}\n\n/**\n * Returns a reference to the callable HTTPS trigger with the specified url.\n * @param url - The url of the trigger.\n * @public\n */\nexport function httpsCallableFromURL<\n RequestData = unknown,\n ResponseData = unknown\n>(\n functionsInstance: Functions,\n url: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return _httpsCallableFromURL<RequestData, ResponseData>(\n getModularInstance<FunctionsService>(functionsInstance as FunctionsService),\n url,\n options\n );\n}\n","/**\n * Cloud Functions for Firebase\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerFunctions } from './config';\n\nexport * from './api';\nexport * from './public-types';\n\nregisterFunctions(fetch.bind(self));\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport { FunctionsService } from './service';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nconst DEFAULT_REGION = 'us-central1';\n\nconst factory: InstanceFactory<'functions-compat'> = (\n container: ComponentContainer,\n { instanceIdentifier: regionOrCustomDomain }: InstanceFactoryOptions\n) => {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const functionsServiceExp = container.getProvider('functions').getImmediate({\n identifier: regionOrCustomDomain ?? DEFAULT_REGION\n });\n\n return new FunctionsService(app, functionsServiceExp);\n};\n\nexport function registerFunctions(): void {\n const namespaceExports = {\n Functions: FunctionsService\n };\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component('functions-compat', factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\n\nimport {\n CONSOLE_CAMPAIGN_ANALYTICS_ENABLED,\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\n\nexport interface MessagePayloadInternal {\n notification?: NotificationPayloadInternal;\n data?: unknown;\n fcmOptions?: FcmOptionsInternal;\n messageType?: MessageType;\n isFirebaseMessaging?: boolean;\n from: string;\n fcmMessageId: string;\n // eslint-disable-next-line camelcase\n collapse_key: string;\n}\n\nexport interface NotificationPayloadInternal extends NotificationOptions {\n title: string;\n // Supported in the Legacy Send API.\n // See:https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.\n // eslint-disable-next-line camelcase\n click_action?: string;\n icon?: string;\n}\n\n// Defined in\n// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions. Note\n// that the keys are sent to the clients in snake cases which we need to convert to camel so it can\n// be exposed as a type to match the Firebase API convention.\nexport interface FcmOptionsInternal {\n link?: string;\n\n // eslint-disable-next-line camelcase\n analytics_label?: string;\n}\n\nexport enum MessageType {\n PUSH_RECEIVED = 'push-received',\n NOTIFICATION_CLICKED = 'notification-clicked'\n}\n\n/** Additional data of a message sent from the FN Console. */\nexport interface ConsoleMessageData {\n [CONSOLE_CAMPAIGN_ID]: string;\n [CONSOLE_CAMPAIGN_TIME]: string;\n [CONSOLE_CAMPAIGN_NAME]?: string;\n [CONSOLE_CAMPAIGN_ANALYTICS_ENABLED]?: '1';\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\nexport const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n\nexport const DEFAULT_VAPID_KEY =\n 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\n\nexport const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\n\n/** Key of FCM Payload in Notification's data field. */\nexport const FCM_MSG = 'FCM_MSG';\n\nexport const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\nexport const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\nexport const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\n/** Set to '1' if Analytics is enabled for the campaign */\nexport const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\nexport const TAG = 'FirebaseMessaging: ';\nexport const MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST = 1000;\nexport const MAX_RETRIES = 3;\nexport const LOG_INTERVAL_IN_MS = 86400000; //24 hour\nexport const DEFAULT_BACKOFF_TIME_MS = 5000;\n\n// FCM log source name registered at Firelog: 'FCM_CLIENT_EVENT_LOGGING'. It uniquely identifies\n// FCM's logging configuration.\nexport const FCM_LOG_SOURCE = 1249;\n\n// Defined as in proto/messaging_event.proto. Neglecting fields that are supported.\nexport const SDK_PLATFORM_WEB = 3;\nexport const EVENT_MESSAGE_DELIVERED = 1;\n\nexport enum MessageType {\n DATA_MESSAGE = 1,\n DISPLAY_NOTIFICATION = 3\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseFunctions, HttpsCallable } from '@firebase/functions-types';\nimport {\n httpsCallable as httpsCallableExp,\n httpsCallableFromURL as httpsCallableFromURLExp,\n connectFunctionsEmulator as useFunctionsEmulatorExp,\n HttpsCallableOptions,\n Functions as FunctionsServiceExp\n} from '@firebase/functions';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport { FirebaseError } from '@firebase/util';\n\nexport class FunctionsService implements FirebaseFunctions, _FirebaseService {\n /**\n * For testing.\n * @internal\n */\n _region: string;\n /**\n * For testing.\n * @internal\n */\n _customDomain: string | null;\n\n constructor(\n public app: FirebaseApp,\n readonly _delegate: FunctionsServiceExp\n ) {\n this._region = this._delegate.region;\n this._customDomain = this._delegate.customDomain;\n }\n httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable {\n return httpsCallableExp(this._delegate, name, options);\n }\n httpsCallableFromURL(\n url: string,\n options?: HttpsCallableOptions\n ): HttpsCallable {\n return httpsCallableFromURLExp(this._delegate, url, options);\n }\n /**\n * Deprecated in pre-modularized repo, does not exist in modularized\n * functions package, need to convert to \"host\" and \"port\" args that\n * `useFunctionsEmulatorExp` takes.\n * @deprecated\n */\n useFunctionsEmulator(origin: string): void {\n const match = origin.match('[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?');\n if (match == null) {\n throw new FirebaseError(\n 'functions',\n 'No origin provided to useFunctionsEmulator()'\n );\n }\n if (match[2] == null) {\n throw new FirebaseError(\n 'functions',\n 'Port missing in origin provided to useFunctionsEmulator()'\n );\n }\n return useFunctionsEmulatorExp(this._delegate, match[1], Number(match[2]));\n }\n useEmulator(host: string, port: number): void {\n return useFunctionsEmulatorExp(this._delegate, host, port);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase from '@firebase/app-compat';\nimport { name, version } from '../package.json';\nimport { registerFunctions } from './register';\nimport * as types from '@firebase/functions-types';\n\nregisterFunctions();\nfirebase.registerVersion(name, version);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n functions: {\n (app?: FirebaseApp): types.FirebaseFunctions;\n Functions: typeof types.FirebaseFunctions;\n };\n }\n interface FirebaseApp {\n functions(regionOrCustomDomain?: string): types.FirebaseFunctions;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function arrayToBase64(array: Uint8Array | ArrayBuffer): string {\n const uint8Array = new Uint8Array(array);\n const base64String = btoa(String.fromCharCode(...uint8Array));\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\nexport function base64ToArray(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n const base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n\n const rawData = atob(base64);\n const outputArray = new Uint8Array(rawData.length);\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deleteDB, openDB } from 'idb';\n\nimport { TokenDetails } from '../interfaces/token-details';\nimport { arrayToBase64 } from './array-base64-translator';\n\n// https://github.com/firebase/firebase-js-sdk/blob/7857c212f944a2a9eb421fd4cb7370181bc034b5/packages/messaging/src/interfaces/token-details.ts\nexport interface V2TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: string | Uint8Array;\n subscription: PushSubscription;\n fcmSenderId: string;\n fcmPushSet: string;\n createTime?: number;\n endpoint?: string;\n auth?: string;\n p256dh?: string;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/6b5b15ce4ea3df5df5df8a8b33a4e41e249c7715/packages/messaging/src/interfaces/token-details.ts\nexport interface V3TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: Uint8Array;\n fcmSenderId: string;\n fcmPushSet: string;\n endpoint: string;\n auth: ArrayBuffer;\n p256dh: ArrayBuffer;\n createTime: number;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/9567dba664732f681fa7fe60f5b7032bb1daf4c9/packages/messaging/src/interfaces/token-details.ts\nexport interface V4TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: Uint8Array;\n fcmSenderId: string;\n endpoint: string;\n auth: ArrayBufferLike;\n p256dh: ArrayBufferLike;\n createTime: number;\n}\n\nconst OLD_DB_NAME = 'fcm_token_details_db';\n/**\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\n * callback is called for all versions of the old DB.\n */\nconst OLD_DB_VERSION = 5;\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\n\nexport async function migrateOldDatabase(\n senderId: string\n): Promise<TokenDetails | null> {\n if ('databases' in indexedDB) {\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\n // typecast when it lands in TS types.\n const databases = await (\n indexedDB as {\n databases(): Promise<Array<{ name: string; version: number }>>;\n }\n ).databases();\n const dbNames = databases.map(db => db.name);\n\n if (!dbNames.includes(OLD_DB_NAME)) {\n // old DB didn't exist, no need to open.\n return null;\n }\n }\n\n let tokenDetails: TokenDetails | null = null;\n\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\n if (oldVersion < 2) {\n // Database too old, skip migration.\n return;\n }\n\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // Database did not exist. Nothing to do.\n return;\n }\n\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\n const value = await objectStore.index('fcmSenderId').get(senderId);\n await objectStore.clear();\n\n if (!value) {\n // No entry in the database, nothing to migrate.\n return;\n }\n\n if (oldVersion === 2) {\n const oldDetails = value as V2TokenDetails;\n\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\n return;\n }\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime ?? Date.now(),\n subscriptionOptions: {\n auth: oldDetails.auth,\n p256dh: oldDetails.p256dh,\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey:\n typeof oldDetails.vapidKey === 'string'\n ? oldDetails.vapidKey\n : arrayToBase64(oldDetails.vapidKey)\n }\n };\n } else if (oldVersion === 3) {\n const oldDetails = value as V3TokenDetails;\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime,\n subscriptionOptions: {\n auth: arrayToBase64(oldDetails.auth),\n p256dh: arrayToBase64(oldDetails.p256dh),\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey: arrayToBase64(oldDetails.vapidKey)\n }\n };\n } else if (oldVersion === 4) {\n const oldDetails = value as V4TokenDetails;\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime,\n subscriptionOptions: {\n auth: arrayToBase64(oldDetails.auth),\n p256dh: arrayToBase64(oldDetails.p256dh),\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey: arrayToBase64(oldDetails.vapidKey)\n }\n };\n }\n }\n });\n db.close();\n\n // Delete all old databases.\n await deleteDB(OLD_DB_NAME);\n await deleteDB('fcm_vapid_details_db');\n await deleteDB('undefined');\n\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\n}\n\nfunction checkTokenDetails(\n tokenDetails: TokenDetails | null\n): tokenDetails is TokenDetails {\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\n return false;\n }\n const { subscriptionOptions } = tokenDetails;\n return (\n typeof tokenDetails.createTime === 'number' &&\n tokenDetails.createTime > 0 &&\n typeof tokenDetails.token === 'string' &&\n tokenDetails.token.length > 0 &&\n typeof subscriptionOptions.auth === 'string' &&\n subscriptionOptions.auth.length > 0 &&\n typeof subscriptionOptions.p256dh === 'string' &&\n subscriptionOptions.p256dh.length > 0 &&\n typeof subscriptionOptions.endpoint === 'string' &&\n subscriptionOptions.endpoint.length > 0 &&\n typeof subscriptionOptions.swScope === 'string' &&\n subscriptionOptions.swScope.length > 0 &&\n typeof subscriptionOptions.vapidKey === 'string' &&\n subscriptionOptions.vapidKey.length > 0\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DBSchema, IDBPDatabase, deleteDB, openDB } from 'idb';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { TokenDetails } from '../interfaces/token-details';\nimport { migrateOldDatabase } from '../helpers/migrate-old-database';\n\n// Exported for tests.\nexport const DATABASE_NAME = 'firebase-messaging-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\n\ninterface MessagingDB extends DBSchema {\n 'firebase-messaging-store': {\n key: string;\n value: TokenDetails;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<MessagingDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<MessagingDB>> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (upgradeDb, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\n // because if there are multiple versions between the old version and the current version, we\n // want ALL the migrations that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\n }\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function dbGet(\n firebaseDependencies: FirebaseInternalDependencies\n): Promise<TokenDetails | undefined> {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tokenDetails = (await db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key)) as TokenDetails;\n\n if (tokenDetails) {\n return tokenDetails;\n } else {\n // Check if there is a tokenDetails object in the old DB.\n const oldTokenDetails = await migrateOldDatabase(\n firebaseDependencies.appConfig.senderId\n );\n if (oldTokenDetails) {\n await dbSet(firebaseDependencies, oldTokenDetails);\n return oldTokenDetails;\n }\n }\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function dbSet(\n firebaseDependencies: FirebaseInternalDependencies,\n tokenDetails: TokenDetails\n): Promise<TokenDetails> {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\n await tx.done;\n return tokenDetails;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function dbRemove(\n firebaseDependencies: FirebaseInternalDependencies\n): Promise<void> {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.done;\n}\n\n/** Deletes the DB. Useful for tests. */\nexport async function dbDelete(): Promise<void> {\n if (dbPromise) {\n (await dbPromise).close();\n await deleteDB(DATABASE_NAME);\n dbPromise = null;\n }\n}\n\nfunction getKey({ appConfig }: FirebaseInternalDependencies): string {\n return appConfig.appId;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n AVAILABLE_IN_WINDOW = 'only-available-in-window',\n AVAILABLE_IN_SW = 'only-available-in-sw',\n PERMISSION_DEFAULT = 'permission-default',\n PERMISSION_BLOCKED = 'permission-blocked',\n UNSUPPORTED_BROWSER = 'unsupported-browser',\n INDEXED_DB_UNSUPPORTED = 'indexed-db-unsupported',\n FAILED_DEFAULT_REGISTRATION = 'failed-service-worker-registration',\n TOKEN_SUBSCRIBE_FAILED = 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN = 'token-subscribe-no-token',\n TOKEN_UNSUBSCRIBE_FAILED = 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED = 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN = 'token-update-no-token',\n INVALID_BG_HANDLER = 'invalid-bg-handler',\n USE_SW_AFTER_GET_TOKEN = 'use-sw-after-get-token',\n INVALID_SW_REGISTRATION = 'invalid-sw-registration',\n USE_VAPID_KEY_AFTER_GET_TOKEN = 'use-vapid-key-after-get-token',\n INVALID_VAPID_KEY = 'invalid-vapid-key'\n}\n\nexport const ERROR_MAP: ErrorMap<ErrorCode> = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.AVAILABLE_IN_WINDOW]:\n 'This method is available in a Window context.',\n [ErrorCode.AVAILABLE_IN_SW]:\n 'This method is available in a service worker context.',\n [ErrorCode.PERMISSION_DEFAULT]:\n 'The notification permission was not granted and dismissed instead.',\n [ErrorCode.PERMISSION_BLOCKED]:\n 'The notification permission was not granted and blocked instead.',\n [ErrorCode.UNSUPPORTED_BROWSER]:\n \"This browser doesn't support the API's required to use the Firebase SDK.\",\n [ErrorCode.INDEXED_DB_UNSUPPORTED]:\n \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]:\n 'We are unable to register the default service worker. {$browserErrorMessage}',\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]:\n 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\n [ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN]:\n 'FCM returned no token when subscribing the user to push.',\n [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]:\n 'A problem occurred while unsubscribing the ' +\n 'user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_FAILED]:\n 'A problem occurred while updating the user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_NO_TOKEN]:\n 'FCM returned no token when updating the user to push.',\n [ErrorCode.USE_SW_AFTER_GET_TOKEN]:\n 'The useServiceWorker() method may only be called once and must be ' +\n 'called before calling getToken() to ensure your service worker is used.',\n [ErrorCode.INVALID_SW_REGISTRATION]:\n 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\n [ErrorCode.INVALID_BG_HANDLER]:\n 'The input to setBackgroundMessageHandler() must be a function.',\n [ErrorCode.INVALID_VAPID_KEY]: 'The public VAPID key must be a string.',\n [ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN]:\n 'The usePublicVapidKey() method may only be called once and must be ' +\n 'called before calling getToken() to ensure your VAPID key is used.'\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]: { browserErrorMessage: string };\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]: { errorInfo: string };\n [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]: { errorInfo: string };\n [ErrorCode.TOKEN_UPDATE_FAILED]: { errorInfo: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n 'messaging',\n 'Messaging',\n ERROR_MAP\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_VAPID_KEY, ENDPOINT } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { SubscriptionOptions, TokenDetails } from '../interfaces/token-details';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\n\nexport interface ApiResponse {\n token?: string;\n error?: { message: string };\n}\n\nexport interface ApiRequestBody {\n web: {\n endpoint: string;\n p256dh: string;\n auth: string;\n applicationPubKey?: string;\n };\n}\n\nexport async function requestGetToken(\n firebaseDependencies: FirebaseInternalDependencies,\n subscriptionOptions: SubscriptionOptions\n): Promise<string> {\n const headers = await getHeaders(firebaseDependencies);\n const body = getBody(subscriptionOptions);\n\n const subscribeOptions = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n let responseData: ApiResponse;\n try {\n const response = await fetch(\n getEndpoint(firebaseDependencies.appConfig),\n subscribeOptions\n );\n responseData = await response.json();\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n errorInfo: (err as Error)?.toString()\n });\n }\n\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n errorInfo: message\n });\n }\n\n if (!responseData.token) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n\n return responseData.token;\n}\n\nexport async function requestUpdateToken(\n firebaseDependencies: FirebaseInternalDependencies,\n tokenDetails: TokenDetails\n): Promise<string> {\n const headers = await getHeaders(firebaseDependencies);\n const body = getBody(tokenDetails.subscriptionOptions!);\n\n const updateOptions = {\n method: 'PATCH',\n headers,\n body: JSON.stringify(body)\n };\n\n let responseData: ApiResponse;\n try {\n const response = await fetch(\n `${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`,\n updateOptions\n );\n responseData = await response.json();\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n errorInfo: (err as Error)?.toString()\n });\n }\n\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n errorInfo: message\n });\n }\n\n if (!responseData.token) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_NO_TOKEN);\n }\n\n return responseData.token;\n}\n\nexport async function requestDeleteToken(\n firebaseDependencies: FirebaseInternalDependencies,\n token: string\n): Promise<void> {\n const headers = await getHeaders(firebaseDependencies);\n\n const unsubscribeOptions = {\n method: 'DELETE',\n headers\n };\n\n try {\n const response = await fetch(\n `${getEndpoint(firebaseDependencies.appConfig)}/${token}`,\n unsubscribeOptions\n );\n const responseData: ApiResponse = await response.json();\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n errorInfo: message\n });\n }\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n errorInfo: (err as Error)?.toString()\n });\n }\n}\n\nfunction getEndpoint({ projectId }: AppConfig): string {\n return `${ENDPOINT}/projects/${projectId!}/registrations`;\n}\n\nasync function getHeaders({\n appConfig,\n installations\n}: FirebaseInternalDependencies): Promise<Headers> {\n const authToken = await installations.getToken();\n\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': appConfig.apiKey!,\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\n });\n}\n\nfunction getBody({\n p256dh,\n auth,\n endpoint,\n vapidKey\n}: SubscriptionOptions): ApiRequestBody {\n const body: ApiRequestBody = {\n web: {\n endpoint,\n auth,\n p256dh\n }\n };\n\n if (vapidKey !== DEFAULT_VAPID_KEY) {\n body.web.applicationPubKey = vapidKey;\n }\n\n return body;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SubscriptionOptions, TokenDetails } from '../interfaces/token-details';\nimport {\n arrayToBase64,\n base64ToArray\n} from '../helpers/array-base64-translator';\nimport { dbGet, dbRemove, dbSet } from './idb-manager';\nimport {\n requestDeleteToken,\n requestGetToken,\n requestUpdateToken\n} from './requests';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { MessagingService } from '../messaging-service';\n\n// UpdateRegistration will be called once every week.\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport async function getTokenInternal(\n messaging: MessagingService\n): Promise<string> {\n const pushSubscription = await getPushSubscription(\n messaging.swRegistration!,\n messaging.vapidKey!\n );\n\n const subscriptionOptions: SubscriptionOptions = {\n vapidKey: messaging.vapidKey!,\n swScope: messaging.swRegistration!.scope,\n endpoint: pushSubscription.endpoint,\n auth: arrayToBase64(pushSubscription.getKey('auth')!),\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh')!)\n };\n\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n if (!tokenDetails) {\n // No token, get a new one.\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\n } else if (\n !isTokenValid(tokenDetails.subscriptionOptions!, subscriptionOptions)\n ) {\n // Invalid token, get a new one.\n try {\n await requestDeleteToken(\n messaging.firebaseDependencies!,\n tokenDetails.token\n );\n } catch (e) {\n // Suppress errors because of #2364\n console.warn(e);\n }\n\n return getNewToken(messaging.firebaseDependencies!, subscriptionOptions);\n } else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\n // Weekly token refresh\n return updateToken(messaging, {\n token: tokenDetails.token,\n createTime: Date.now(),\n subscriptionOptions\n });\n } else {\n // Valid token, nothing to do.\n return tokenDetails.token;\n }\n}\n\n/**\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\n * the push subscription if it exists.\n */\nexport async function deleteTokenInternal(\n messaging: MessagingService\n): Promise<boolean> {\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n if (tokenDetails) {\n await requestDeleteToken(\n messaging.firebaseDependencies,\n tokenDetails.token\n );\n await dbRemove(messaging.firebaseDependencies);\n }\n\n // Unsubscribe from the push subscription.\n const pushSubscription =\n await messaging.swRegistration!.pushManager.getSubscription();\n if (pushSubscription) {\n return pushSubscription.unsubscribe();\n }\n\n // If there's no SW, consider it a success.\n return true;\n}\n\nasync function updateToken(\n messaging: MessagingService,\n tokenDetails: TokenDetails\n): Promise<string> {\n try {\n const updatedToken = await requestUpdateToken(\n messaging.firebaseDependencies,\n tokenDetails\n );\n\n const updatedTokenDetails: TokenDetails = {\n ...tokenDetails,\n token: updatedToken,\n createTime: Date.now()\n };\n\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\n return updatedToken;\n } catch (e) {\n await deleteTokenInternal(messaging);\n throw e;\n }\n}\n\nasync function getNewToken(\n firebaseDependencies: FirebaseInternalDependencies,\n subscriptionOptions: SubscriptionOptions\n): Promise<string> {\n const token = await requestGetToken(\n firebaseDependencies,\n subscriptionOptions\n );\n const tokenDetails: TokenDetails = {\n token,\n createTime: Date.now(),\n subscriptionOptions\n };\n await dbSet(firebaseDependencies, tokenDetails);\n return tokenDetails.token;\n}\n\n/**\n * Gets a PushSubscription for the current user.\n */\nasync function getPushSubscription(\n swRegistration: ServiceWorkerRegistration,\n vapidKey: string\n): Promise<PushSubscription> {\n const subscription = await swRegistration.pushManager.getSubscription();\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\n // submitted to pushManager#subscribe must be of type Uint8Array.\n applicationServerKey: base64ToArray(vapidKey)\n });\n}\n\n/**\n * Checks if the saved tokenDetails object matches the configuration provided.\n */\nfunction isTokenValid(\n dbOptions: SubscriptionOptions,\n currentOptions: SubscriptionOptions\n): boolean {\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\n\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MessagePayload } from '../interfaces/public-types';\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\n\nexport function externalizePayload(\n internalPayload: MessagePayloadInternal\n): MessagePayload {\n const payload: MessagePayload = {\n from: internalPayload.from,\n // eslint-disable-next-line camelcase\n collapseKey: internalPayload.collapse_key,\n // eslint-disable-next-line camelcase\n messageId: internalPayload.fcmMessageId\n } as MessagePayload;\n\n propagateNotificationPayload(payload, internalPayload);\n propagateDataPayload(payload, internalPayload);\n propagateFcmOptions(payload, internalPayload);\n\n return payload;\n}\n\nfunction propagateNotificationPayload(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n if (!messagePayloadInternal.notification) {\n return;\n }\n\n payload.notification = {};\n\n const title = messagePayloadInternal.notification!.title;\n if (!!title) {\n payload.notification!.title = title;\n }\n\n const body = messagePayloadInternal.notification!.body;\n if (!!body) {\n payload.notification!.body = body;\n }\n\n const image = messagePayloadInternal.notification!.image;\n if (!!image) {\n payload.notification!.image = image;\n }\n\n const icon = messagePayloadInternal.notification!.icon;\n if (!!icon) {\n payload.notification!.icon = icon;\n }\n}\n\nfunction propagateDataPayload(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n if (!messagePayloadInternal.data) {\n return;\n }\n\n payload.data = messagePayloadInternal.data as { [key: string]: string };\n}\n\nfunction propagateFcmOptions(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\n if (\n !messagePayloadInternal.fcmOptions &&\n !messagePayloadInternal.notification?.click_action\n ) {\n return;\n }\n\n payload.fcmOptions = {};\n\n const link =\n messagePayloadInternal.fcmOptions?.link ??\n messagePayloadInternal.notification?.click_action;\n\n if (!!link) {\n payload.fcmOptions!.link = link;\n }\n\n // eslint-disable-next-line camelcase\n const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;\n if (!!analyticsLabel) {\n payload.fcmOptions!.analyticsLabel = analyticsLabel;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_BACKOFF_TIME_MS,\n EVENT_MESSAGE_DELIVERED,\n FCM_LOG_SOURCE,\n LOG_INTERVAL_IN_MS,\n MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST,\n MAX_RETRIES,\n MessageType,\n SDK_PLATFORM_WEB\n} from '../util/constants';\nimport {\n FcmEvent,\n LogEvent,\n LogRequest,\n LogResponse\n} from '../interfaces/logging-types';\n\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\nimport { MessagingService } from '../messaging-service';\n\nconst FIRELOG_ENDPOINT = _mergeStrings(\n 'hts/frbslgigp.ogepscmv/ieo/eaylg',\n 'tp:/ieaeogn-agolai.o/1frlglgc/o'\n);\n\nconst FCM_TRANSPORT_KEY = _mergeStrings(\n 'AzSCbw63g1R0nCw85jG8',\n 'Iaya3yLKwmgvh7cF0q4'\n);\n\nexport function startLoggingService(messaging: MessagingService): void {\n if (!messaging.isLogServiceStarted) {\n _processQueue(messaging, LOG_INTERVAL_IN_MS);\n messaging.isLogServiceStarted = true;\n }\n}\n\n/**\n *\n * @param messaging the messaging instance.\n * @param offsetInMs this method execute after `offsetInMs` elapsed .\n */\nexport function _processQueue(\n messaging: MessagingService,\n offsetInMs: number\n): void {\n setTimeout(async () => {\n if (!messaging.deliveryMetricsExportedToBigQueryEnabled) {\n // flush events and terminate logging service\n messaging.logEvents = [];\n messaging.isLogServiceStarted = false;\n\n return;\n }\n\n if (!messaging.logEvents.length) {\n return _processQueue(messaging, LOG_INTERVAL_IN_MS);\n }\n\n await _dispatchLogEvents(messaging);\n }, offsetInMs);\n}\n\nexport async function _dispatchLogEvents(\n messaging: MessagingService\n): Promise<void> {\n for (\n let i = 0, n = messaging.logEvents.length;\n i < n;\n i += MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST\n ) {\n const logRequest = _createLogRequest(\n messaging.logEvents.slice(i, i + MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST)\n );\n\n let retryCount = 0,\n response = {} as Response;\n\n do {\n try {\n response = await fetch(\n FIRELOG_ENDPOINT.concat('?key=', FCM_TRANSPORT_KEY),\n {\n method: 'POST',\n body: JSON.stringify(logRequest)\n }\n );\n\n // don't retry on 200s or non retriable errors\n if (response.ok || (!response.ok && !isRetriableError(response))) {\n break;\n }\n\n if (!response.ok && isRetriableError(response)) {\n // rethrow to retry with quota\n throw new Error(\n 'a retriable Non-200 code is returned in fetch to Firelog endpoint. Retry'\n );\n }\n } catch (error) {\n const isLastAttempt = retryCount === MAX_RETRIES;\n if (isLastAttempt) {\n // existing the do-while interactive retry logic because retry quota has reached.\n break;\n }\n }\n\n let delayInMs: number;\n try {\n delayInMs = Number(\n ((await response.json()) as LogResponse).nextRequestWaitMillis\n );\n } catch (e) {\n delayInMs = DEFAULT_BACKOFF_TIME_MS;\n }\n\n await new Promise(resolve => setTimeout(resolve, delayInMs));\n\n retryCount++;\n } while (retryCount < MAX_RETRIES);\n }\n\n messaging.logEvents = [];\n // schedule for next logging\n _processQueue(messaging, LOG_INTERVAL_IN_MS);\n}\n\nfunction isRetriableError(response: Response): boolean {\n const httpStatus = response.status;\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\nexport async function stageLog(\n messaging: MessagingService,\n internalPayload: MessagePayloadInternal\n): Promise<void> {\n const fcmEvent = createFcmEvent(\n internalPayload,\n await messaging.firebaseDependencies.installations.getId()\n );\n\n createAndEnqueueLogEvent(messaging, fcmEvent);\n}\n\nfunction createFcmEvent(\n internalPayload: MessagePayloadInternal,\n fid: string\n): FcmEvent {\n const fcmEvent = {} as FcmEvent;\n\n /* eslint-disable camelcase */\n // some fields should always be non-null. Still check to ensure.\n if (!!internalPayload.from) {\n fcmEvent.project_number = internalPayload.from;\n }\n\n if (!!internalPayload.fcmMessageId) {\n fcmEvent.message_id = internalPayload.fcmMessageId;\n }\n\n fcmEvent.instance_id = fid;\n\n if (!!internalPayload.notification) {\n fcmEvent.message_type = MessageType.DISPLAY_NOTIFICATION.toString();\n } else {\n fcmEvent.message_type = MessageType.DATA_MESSAGE.toString();\n }\n\n fcmEvent.sdk_platform = SDK_PLATFORM_WEB.toString();\n fcmEvent.package_name = self.origin.replace(/(^\\w+:|^)\\/\\//, '');\n\n if (!!internalPayload.collapse_key) {\n fcmEvent.collapse_key = internalPayload.collapse_key;\n }\n\n fcmEvent.event = EVENT_MESSAGE_DELIVERED.toString();\n\n if (!!internalPayload.fcmOptions?.analytics_label) {\n fcmEvent.analytics_label = internalPayload.fcmOptions?.analytics_label;\n }\n\n /* eslint-enable camelcase */\n return fcmEvent;\n}\n\nfunction createAndEnqueueLogEvent(\n messaging: MessagingService,\n fcmEvent: FcmEvent\n): void {\n const logEvent = {} as LogEvent;\n\n /* eslint-disable camelcase */\n logEvent.event_time_ms = Math.floor(Date.now()).toString();\n logEvent.source_extension_json_proto3 = JSON.stringify(fcmEvent);\n // eslint-disable-next-line camelcase\n\n messaging.logEvents.push(logEvent);\n}\n\nexport function _createLogRequest(logEventQueue: LogEvent[]): LogRequest {\n const logRequest = {} as LogRequest;\n\n /* eslint-disable camelcase */\n logRequest.log_source = FCM_LOG_SOURCE.toString();\n logRequest.log_event = logEventQueue;\n /* eslint-enable camelcase */\n\n return logRequest;\n}\n\nexport function _mergeStrings(s1: string, s2: string): string {\n const resultArray = [];\n for (let i = 0; i < s1.length; i++) {\n resultArray.push(s1.charAt(i));\n if (i < s2.length) {\n resultArray.push(s2.charAt(i));\n }\n }\n\n return resultArray.join('');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseError } from '@firebase/util';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration Object');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: ReadonlyArray<keyof FirebaseOptions> = [\n 'projectId',\n 'apiKey',\n 'appId',\n 'messagingSenderId'\n ];\n\n const { options } = app;\n for (const keyName of configKeys) {\n if (!options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: options.projectId!,\n apiKey: options.apiKey!,\n appId: options.appId!,\n senderId: options.messagingSenderId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { MessagePayload, NextFn, Observer } from './interfaces/public-types';\n\nimport { FirebaseAnalyticsInternalName } from '@firebase/analytics-interop-types';\nimport { FirebaseInternalDependencies } from './interfaces/internal-dependencies';\nimport { LogEvent } from './interfaces/logging-types';\nimport { Provider } from '@firebase/component';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { extractAppConfig } from './helpers/extract-app-config';\n\nexport class MessagingService implements _FirebaseService {\n readonly app!: FirebaseApp;\n readonly firebaseDependencies!: FirebaseInternalDependencies;\n\n swRegistration?: ServiceWorkerRegistration;\n vapidKey?: string;\n // logging is only done with end user consent. Default to false.\n deliveryMetricsExportedToBigQueryEnabled: boolean = false;\n\n onBackgroundMessageHandler:\n | NextFn<MessagePayload>\n | Observer<MessagePayload>\n | null = null;\n\n onMessageHandler: NextFn<MessagePayload> | Observer<MessagePayload> | null =\n null;\n\n logEvents: LogEvent[] = [];\n isLogServiceStarted: boolean = false;\n\n constructor(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n analyticsProvider: Provider<FirebaseAnalyticsInternalName>\n ) {\n const appConfig = extractAppConfig(app);\n\n this.firebaseDependencies = {\n app,\n appConfig,\n installations,\n analyticsProvider\n };\n }\n\n _delete(): Promise<void> {\n return Promise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_SW_PATH, DEFAULT_SW_SCOPE } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function registerDefaultSw(\n messaging: MessagingService\n): Promise<void> {\n try {\n messaging.swRegistration = await navigator.serviceWorker.register(\n DEFAULT_SW_PATH,\n {\n scope: DEFAULT_SW_SCOPE\n }\n );\n\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\n // is stuck with the old version. For example,\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\n // sw if there was an update.\n messaging.swRegistration.update().catch(() => {\n /* it is non blocking and we don't care if it failed */\n });\n } catch (e) {\n throw ERROR_FACTORY.create(ErrorCode.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: (e as Error)?.message\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { getTokenInternal } from '../internals/token-manager';\nimport { updateSwReg } from '../helpers/updateSwReg';\nimport { updateVapidKey } from '../helpers/updateVapidKey';\nimport { GetTokenOptions } from '../interfaces/public-types';\n\nexport async function getToken(\n messaging: MessagingService,\n options?: GetTokenOptions\n): Promise<string> {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n if (Notification.permission === 'default') {\n await Notification.requestPermission();\n }\n\n if (Notification.permission !== 'granted') {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n }\n\n await updateVapidKey(messaging, options?.vapidKey);\n await updateSwReg(messaging, options?.serviceWorkerRegistration);\n\n return getTokenInternal(messaging);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_VAPID_KEY } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\n\nexport async function updateVapidKey(\n messaging: MessagingService,\n vapidKey?: string | undefined\n): Promise<void> {\n if (!!vapidKey) {\n messaging.vapidKey = vapidKey;\n } else if (!messaging.vapidKey) {\n messaging.vapidKey = DEFAULT_VAPID_KEY;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { registerDefaultSw } from './registerDefaultSw';\n\nexport async function updateSwReg(\n messaging: MessagingService,\n swRegistration?: ServiceWorkerRegistration | undefined\n): Promise<void> {\n if (!swRegistration && !messaging.swRegistration) {\n await registerDefaultSw(messaging);\n }\n\n if (!swRegistration && !!messaging.swRegistration) {\n return;\n }\n\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_SW_REGISTRATION);\n }\n\n messaging.swRegistration = swRegistration;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\nimport {\n ConsoleMessageData,\n MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function logToScion(\n messaging: MessagingService,\n messageType: MessageType,\n data: ConsoleMessageData\n): Promise<void> {\n const eventType = getEventType(messageType);\n const analytics =\n await messaging.firebaseDependencies.analyticsProvider.get();\n analytics.logEvent(eventType, {\n /* eslint-disable camelcase */\n message_id: data[CONSOLE_CAMPAIGN_ID],\n message_name: data[CONSOLE_CAMPAIGN_NAME],\n message_time: data[CONSOLE_CAMPAIGN_TIME],\n message_device_time: Math.floor(Date.now() / 1000)\n /* eslint-enable camelcase */\n });\n}\n\nfunction getEventType(messageType: MessageType): string {\n switch (messageType) {\n case MessageType.NOTIFICATION_CLICKED:\n return 'notification_open';\n case MessageType.PUSH_RECEIVED:\n return 'notification_foreground';\n default:\n throw new Error();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MessagePayloadInternal,\n MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { CONSOLE_CAMPAIGN_ANALYTICS_ENABLED } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\nimport { externalizePayload } from '../helpers/externalizePayload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { logToScion } from '../helpers/logToScion';\n\nexport async function messageEventListener(\n messaging: MessagingService,\n event: MessageEvent\n): Promise<void> {\n const internalPayload = event.data as MessagePayloadInternal;\n\n if (!internalPayload.isFirebaseMessaging) {\n return;\n }\n\n if (\n messaging.onMessageHandler &&\n internalPayload.messageType === MessageType.PUSH_RECEIVED\n ) {\n if (typeof messaging.onMessageHandler === 'function') {\n messaging.onMessageHandler(externalizePayload(internalPayload));\n } else {\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\n }\n }\n\n // Log to Scion if applicable\n const dataPayload = internalPayload.data;\n if (\n isConsoleMessage(dataPayload) &&\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1'\n ) {\n await logToScion(messaging, internalPayload.messageType!, dataPayload);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSOLE_CAMPAIGN_ID } from '../util/constants';\nimport { ConsoleMessageData } from '../interfaces/internal-message-payload';\n\nexport function isConsoleMessage(data: unknown): data is ConsoleMessageData {\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport {\n onNotificationClick,\n onPush,\n onSubChange\n} from '../listeners/sw-listeners';\n\nimport { GetTokenOptions } from '../interfaces/public-types';\nimport { MessagingInternal } from '@firebase/messaging-interop-types';\nimport { MessagingService } from '../messaging-service';\nimport { ServiceWorkerGlobalScope } from '../util/sw-types';\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport { getToken } from '../api/getToken';\nimport { messageEventListener } from '../listeners/window-listener';\n\nimport { name, version } from '../../package.json';\n\nconst WindowMessagingFactory: InstanceFactory<'messaging'> = (\n container: ComponentContainer\n) => {\n const messaging = new MessagingService(\n container.getProvider('app').getImmediate(),\n container.getProvider('installations-internal').getImmediate(),\n container.getProvider('analytics-internal')\n );\n\n navigator.serviceWorker.addEventListener('message', e =>\n messageEventListener(messaging as MessagingService, e)\n );\n\n return messaging;\n};\n\nconst WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (\n container: ComponentContainer\n) => {\n const messaging = container\n .getProvider('messaging')\n .getImmediate() as MessagingService;\n\n const messagingInternal: MessagingInternal = {\n getToken: (options?: GetTokenOptions) => getToken(messaging, options)\n };\n\n return messagingInternal;\n};\n\ndeclare const self: ServiceWorkerGlobalScope;\nconst SwMessagingFactory: InstanceFactory<'messaging'> = (\n container: ComponentContainer\n) => {\n const messaging = new MessagingService(\n container.getProvider('app').getImmediate(),\n container.getProvider('installations-internal').getImmediate(),\n container.getProvider('analytics-internal')\n );\n\n self.addEventListener('push', e => {\n e.waitUntil(onPush(e, messaging as MessagingService));\n });\n self.addEventListener('pushsubscriptionchange', e => {\n e.waitUntil(onSubChange(e, messaging as MessagingService));\n });\n self.addEventListener('notificationclick', e => {\n e.waitUntil(onNotificationClick(e));\n });\n\n return messaging;\n};\n\nexport function registerMessagingInWindow(): void {\n _registerComponent(\n new Component('messaging', WindowMessagingFactory, ComponentType.PUBLIC)\n );\n\n _registerComponent(\n new Component(\n 'messaging-internal',\n WindowMessagingInternalFactory,\n ComponentType.PRIVATE\n )\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\n/**\n * The messaging instance registered in sw is named differently than that of in client. This is\n * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in\n * `messaging-compat` and component with the same name can only be registered once.\n */\nexport function registerMessagingInSw(): void {\n _registerComponent(\n new Component('messaging-sw', SwMessagingFactory, ComponentType.PUBLIC)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from './util/errors';\nimport { FirebaseApp, _getProvider, getApp } from '@firebase/app';\nimport {\n GetTokenOptions,\n MessagePayload,\n Messaging\n} from './interfaces/public-types';\nimport {\n NextFn,\n Observer,\n Unsubscribe,\n getModularInstance\n} from '@firebase/util';\nimport { isSwSupported, isWindowSupported } from './api/isSupported';\n\nimport { MessagingService } from './messaging-service';\nimport { deleteToken as _deleteToken } from './api/deleteToken';\nimport { getToken as _getToken } from './api/getToken';\nimport { onBackgroundMessage as _onBackgroundMessage } from './api/onBackgroundMessage';\nimport { onMessage as _onMessage } from './api/onMessage';\nimport { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryMetricsExportedToBigQueryEnabled';\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInWindow(app: FirebaseApp = getApp()): Messaging {\n // Conscious decision to make this async check non-blocking during the messaging instance\n // initialization phase for performance consideration. An error would be thrown latter for\n // developer's information. Developers can then choose to import and call `isSupported` for\n // special handling.\n isWindowSupported().then(\n isSupported => {\n // If `isWindowSupported()` resolved, but returned false.\n if (!isSupported) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n },\n _ => {\n // If `isWindowSupported()` rejected.\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n }\n );\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\n}\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInSw(app: FirebaseApp = getApp()): Messaging {\n // Conscious decision to make this async check non-blocking during the messaging instance\n // initialization phase for performance consideration. An error would be thrown latter for\n // developer's information. Developers can then choose to import and call `isSupported` for\n // special handling.\n isSwSupported().then(\n isSupported => {\n // If `isSwSupported()` resolved, but returned false.\n if (!isSupported) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n },\n _ => {\n // If `isSwSupported()` rejected.\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n }\n );\n return _getProvider(getModularInstance(app), 'messaging-sw').getImmediate();\n}\n\n/**\n * Subscribes the {@link Messaging} instance to push notifications. Returns an Firebase Cloud\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\n * instance.\n *\n * If a notification permission isn't already granted, this method asks the user for permission. The\n * returned promise rejects if the user does not allow the app to show notifications.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param options - Provides an optional vapid key and an optinoal service worker registration\n *\n * @returns The promise resolves with an FCM registration token.\n *\n * @public\n */\nexport async function getToken(\n messaging: Messaging,\n options?: GetTokenOptions\n): Promise<string> {\n messaging = getModularInstance(messaging);\n return _getToken(messaging as MessagingService, options);\n}\n\n/**\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\n * the {@link Messaging} instance from the push subscription.\n *\n * @param messaging - The {@link Messaging} instance.\n *\n * @returns The promise resolves when the token has been successfully deleted.\n *\n * @public\n */\nexport function deleteToken(messaging: Messaging): Promise<boolean> {\n messaging = getModularInstance(messaging);\n return _deleteToken(messaging as MessagingService);\n}\n\n/**\n * When a push message is received and the user is currently on a page for your origin, the\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\n * the push message.\n *\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined,\n * is called when a message is received and the user is currently viewing your page.\n * @returns To stop listening for messages execute this returned function.\n *\n * @public\n */\nexport function onMessage(\n messaging: Messaging,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n messaging = getModularInstance(messaging);\n return _onMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Called when a message is received while the app is in the background. An app is considered to be\n * in the background if no active window is displayed.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined, is called when a\n * message is received and the app is currently in the background.\n *\n * @returns To stop listening for messages execute this returned function\n *\n * @public\n */\nexport function onBackgroundMessage(\n messaging: Messaging,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n messaging = getModularInstance(messaging);\n return _onBackgroundMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By\n * default, message delivery metrics are not exported to BigQuery. Use this method to enable or\n * disable the export at runtime.\n *\n * @param messaging - The `FirebaseMessaging` instance.\n * @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to\n * BigQuery.\n *\n * @public\n */\nexport function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(\n messaging: Messaging,\n enable: boolean\n): void {\n messaging = getModularInstance(messaging);\n return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { deleteTokenInternal } from '../internals/token-manager';\nimport { registerDefaultSw } from '../helpers/registerDefaultSw';\n\nexport async function deleteToken(\n messaging: MessagingService\n): Promise<boolean> {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n if (!messaging.swRegistration) {\n await registerDefaultSw(messaging);\n }\n\n return deleteTokenInternal(messaging);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport {\n MessagePayload,\n NextFn,\n Observer,\n Unsubscribe\n} from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\nexport function onMessage(\n messaging: MessagingService,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n messaging.onMessageHandler = nextOrObserver;\n\n return () => {\n messaging.onMessageHandler = null;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_VAPID_KEY, FCM_MSG } from '../util/constants';\nimport {\n MessagePayloadInternal,\n MessageType,\n NotificationPayloadInternal\n} from '../interfaces/internal-message-payload';\nimport {\n NotificationEvent,\n PushEvent,\n PushSubscriptionChangeEvent,\n ServiceWorkerGlobalScope,\n WindowClient\n} from '../util/sw-types';\nimport {\n deleteTokenInternal,\n getTokenInternal\n} from '../internals/token-manager';\n\nimport { MessagingService } from '../messaging-service';\nimport { dbGet } from '../internals/idb-manager';\nimport { externalizePayload } from '../helpers/externalizePayload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { sleep } from '../helpers/sleep';\nimport { stageLog } from '../helpers/logToFirelog';\n\n// maxActions is an experimental property and not part of the official\n// TypeScript interface\n// https://developer.mozilla.org/en-US/docs/Web/API/Notification/maxActions\ninterface NotificationExperimental extends Notification {\n maxActions?: number;\n}\n\n// Let TS know that this is a service worker\ndeclare const self: ServiceWorkerGlobalScope;\n\nexport async function onSubChange(\n event: PushSubscriptionChangeEvent,\n messaging: MessagingService\n): Promise<void> {\n const { newSubscription } = event;\n if (!newSubscription) {\n // Subscription revoked, delete token\n await deleteTokenInternal(messaging);\n return;\n }\n\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n await deleteTokenInternal(messaging);\n\n messaging.vapidKey =\n tokenDetails?.subscriptionOptions?.vapidKey ?? DEFAULT_VAPID_KEY;\n await getTokenInternal(messaging);\n}\n\nexport async function onPush(\n event: PushEvent,\n messaging: MessagingService\n): Promise<void> {\n const internalPayload = getMessagePayloadInternal(event);\n if (!internalPayload) {\n // Failed to get parsed MessagePayload from the PushEvent. Skip handling the push.\n return;\n }\n\n // log to Firelog with user consent\n if (messaging.deliveryMetricsExportedToBigQueryEnabled) {\n await stageLog(messaging, internalPayload);\n }\n\n // foreground handling: eventually passed to onMessage hook\n const clientList = await getClientList();\n if (hasVisibleClients(clientList)) {\n return sendMessagePayloadInternalToWindows(clientList, internalPayload);\n }\n\n // background handling: display if possible and pass to onBackgroundMessage hook\n if (!!internalPayload.notification) {\n await showNotification(wrapInternalPayload(internalPayload));\n }\n\n if (!messaging) {\n return;\n }\n\n if (!!messaging.onBackgroundMessageHandler) {\n const payload = externalizePayload(internalPayload);\n\n if (typeof messaging.onBackgroundMessageHandler === 'function') {\n await messaging.onBackgroundMessageHandler(payload);\n } else {\n messaging.onBackgroundMessageHandler.next(payload);\n }\n }\n}\n\nexport async function onNotificationClick(\n event: NotificationEvent\n): Promise<void> {\n const internalPayload: MessagePayloadInternal =\n event.notification?.data?.[FCM_MSG];\n\n if (!internalPayload) {\n return;\n } else if (event.action) {\n // User clicked on an action button. This will allow developers to act on action button clicks\n // by using a custom onNotificationClick listener that they define.\n return;\n }\n\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n\n // Note clicking on a notification with no link set will focus the Chrome's current tab.\n const link = getLink(internalPayload);\n if (!link) {\n return;\n }\n\n // FM should only open/focus links from app's origin.\n const url = new URL(link, self.location.href);\n const originUrl = new URL(self.location.origin);\n\n if (url.host !== originUrl.host) {\n return;\n }\n\n let client = await getWindowClient(url);\n\n if (!client) {\n client = await self.clients.openWindow(link);\n\n // Wait three seconds for the client to initialize and set up the message handler so that it\n // can receive the message.\n await sleep(3000);\n } else {\n client = await client.focus();\n }\n\n if (!client) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n\n internalPayload.messageType = MessageType.NOTIFICATION_CLICKED;\n internalPayload.isFirebaseMessaging = true;\n return client.postMessage(internalPayload);\n}\n\nfunction wrapInternalPayload(\n internalPayload: MessagePayloadInternal\n): NotificationPayloadInternal {\n const wrappedInternalPayload: NotificationPayloadInternal = {\n ...(internalPayload.notification as unknown as NotificationPayloadInternal)\n };\n\n // Put the message payload under FCM_MSG name so we can identify the notification as being an FCM\n // notification vs a notification from somewhere else (i.e. normal web push or developer generated\n // notification).\n wrappedInternalPayload.data = {\n [FCM_MSG]: internalPayload\n };\n\n return wrappedInternalPayload;\n}\n\nfunction getMessagePayloadInternal({\n data\n}: PushEvent): MessagePayloadInternal | null {\n if (!data) {\n return null;\n }\n\n try {\n return data.json();\n } catch (err) {\n // Not JSON so not an FCM message.\n return null;\n }\n}\n\n/**\n * @param url The URL to look for when focusing a client.\n * @return Returns an existing window client or a newly opened WindowClient.\n */\nasync function getWindowClient(url: URL): Promise<WindowClient | null> {\n const clientList = await getClientList();\n\n for (const client of clientList) {\n const clientUrl = new URL(client.url, self.location.href);\n\n if (url.host === clientUrl.host) {\n return client;\n }\n }\n\n return null;\n}\n\n/**\n * @returns If there is currently a visible WindowClient, this method will resolve to true,\n * otherwise false.\n */\nfunction hasVisibleClients(clientList: WindowClient[]): boolean {\n return clientList.some(\n client =>\n client.visibilityState === 'visible' &&\n // Ignore chrome-extension clients as that matches the background pages of extensions, which\n // are always considered visible for some reason.\n !client.url.startsWith('chrome-extension://')\n );\n}\n\nfunction sendMessagePayloadInternalToWindows(\n clientList: WindowClient[],\n internalPayload: MessagePayloadInternal\n): void {\n internalPayload.isFirebaseMessaging = true;\n internalPayload.messageType = MessageType.PUSH_RECEIVED;\n\n for (const client of clientList) {\n client.postMessage(internalPayload);\n }\n}\n\nfunction getClientList(): Promise<WindowClient[]> {\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n // TS doesn't know that \"type: 'window'\" means it'll return WindowClient[]\n }) as Promise<WindowClient[]>;\n}\n\nfunction showNotification(\n notificationPayloadInternal: NotificationPayloadInternal\n): Promise<void> {\n // Note: Firefox does not support the maxActions property.\n // https://developer.mozilla.org/en-US/docs/Web/API/notification/maxActions\n const { actions } = notificationPayloadInternal;\n const { maxActions } = Notification as unknown as NotificationExperimental;\n if (actions && maxActions && actions.length > maxActions) {\n console.warn(\n `This browser only supports ${maxActions} actions. The remaining actions will not be displayed.`\n );\n }\n\n return self.registration.showNotification(\n /* title= */ notificationPayloadInternal.title ?? '',\n notificationPayloadInternal\n );\n}\n\nfunction getLink(payload: MessagePayloadInternal): string | null {\n // eslint-disable-next-line camelcase\n const link = payload.fcmOptions?.link ?? payload.notification?.click_action;\n if (link) {\n return link;\n }\n\n if (isConsoleMessage(payload.data)) {\n // Notification created in the Firebase Console. Redirect to origin.\n return self.location.origin;\n } else {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport {\n MessagePayload,\n NextFn,\n Observer,\n Unsubscribe\n} from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\nexport function onBackgroundMessage(\n messaging: MessagingService,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n if (self.document !== undefined) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_SW);\n }\n\n messaging.onBackgroundMessageHandler = nextOrObserver;\n\n return () => {\n messaging.onBackgroundMessageHandler = null;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Network headers */\nexport type Headers = Record<string, string>;\n\n/** Response type exposed by the networking APIs. */\nexport type ConnectionType =\n | string\n | ArrayBuffer\n | Blob\n | NodeJS.ReadableStream;\n\n/**\n * A lightweight wrapper around XMLHttpRequest with a\n * goog.net.XhrIo-like interface.\n *\n * You can create a new connection by invoking `newTextConnection()`,\n * `newBytesConnection()` or `newStreamConnection()`.\n */\nexport interface Connection<T extends ConnectionType> {\n /**\n * Sends a request to the provided URL.\n *\n * This method never rejects its promise. In case of encountering an error,\n * it sets an error code internally which can be accessed by calling\n * getErrorCode() by callers.\n */\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise<void>;\n\n getErrorCode(): ErrorCode;\n\n getStatus(): number;\n\n getResponse(): T;\n\n getErrorText(): string;\n\n /**\n * Abort the request.\n */\n abort(): void;\n\n getResponseHeader(header: string): string | null;\n\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void;\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void;\n}\n\n/**\n * Error codes for requests made by the the XhrIo wrapper.\n */\nexport enum ErrorCode {\n NO_ERROR = 0,\n NETWORK_ERROR = 1,\n ABORT = 2\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport {\n StringFormat,\n _TaskEvent as TaskEvent,\n _TaskState as TaskState\n} from '@firebase/storage';\n\nimport { ReferenceCompat } from './reference';\nimport { StorageServiceCompat } from './service';\nimport * as types from '@firebase/storage-types';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\n/**\n * Type constant for Firebase Storage.\n */\nconst STORAGE_TYPE = 'storage-compat';\n\nfunction factory(\n container: ComponentContainer,\n { instanceIdentifier: url }: InstanceFactoryOptions\n): types.FirebaseStorage {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const storageExp = container\n .getProvider('storage')\n .getImmediate({ identifier: url });\n\n const storageServiceCompat: StorageServiceCompat = new StorageServiceCompat(\n app,\n storageExp\n );\n return storageServiceCompat;\n}\n\nexport function registerStorage(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n TaskState,\n TaskEvent,\n StringFormat,\n Storage: StorageServiceCompat,\n Reference: ReferenceCompat\n };\n instance.INTERNAL.registerComponent(\n new Component(STORAGE_TYPE, factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterStorage(firebase as unknown as _FirebaseNamespace);\n\n/**\n * Define extension behavior for `registerStorage`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n storage?: {\n (app?: FirebaseApp, url?: string): types.FirebaseStorage;\n Storage: typeof types.FirebaseStorage;\n\n StringFormat: {\n BASE64: types.StringFormat;\n BASE64URL: types.StringFormat;\n DATA_URL: types.StringFormat;\n RAW: types.StringFormat;\n };\n TaskEvent: {\n STATE_CHANGED: types.TaskEvent;\n };\n TaskState: {\n CANCELED: types.TaskState;\n ERROR: types.TaskState;\n PAUSED: types.TaskState;\n RUNNING: types.TaskState;\n SUCCESS: types.TaskState;\n };\n };\n }\n interface FirebaseApp {\n storage?(storageBucket?: string): types.FirebaseStorage;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp as AppCompat,\n _FirebaseService\n} from '@firebase/app-compat';\nimport {\n Messaging,\n MessagePayload,\n deleteToken,\n getToken,\n onMessage\n} from '@firebase/messaging';\nimport {\n areCookiesEnabled,\n isIndexedDBAvailable,\n NextFn,\n Observer,\n Unsubscribe\n} from '@firebase/util';\n\nimport { onBackgroundMessage } from '@firebase/messaging/sw';\n\nexport interface MessagingCompat {\n getToken(options?: {\n vapidKey?: string;\n serviceWorkerRegistration?: ServiceWorkerRegistration;\n }): Promise<string>;\n\n deleteToken(): Promise<boolean>;\n\n onMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe;\n\n onBackgroundMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe;\n}\n\nexport function isSupported(): boolean {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // Running in ServiceWorker context\n return isSwSupported();\n } else {\n // Assume we are in the window context.\n return isWindowSupported();\n }\n}\n\n/**\n * Checks to see if the required APIs exist.\n * Unlike the modular version, it does not check if IndexedDB.open() is allowed\n * in order to keep isSupported() synchronous and maintain v8 compatibility.\n */\nfunction isWindowSupported(): boolean {\n return (\n typeof window !== 'undefined' &&\n isIndexedDBAvailable() &&\n areCookiesEnabled() &&\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n}\n\n/**\n * Checks to see if the required APIs exist within SW Context.\n */\nfunction isSwSupported(): boolean {\n return (\n isIndexedDBAvailable() &&\n 'PushManager' in self &&\n 'Notification' in self &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n}\n\nexport class MessagingCompatImpl implements MessagingCompat, _FirebaseService {\n constructor(readonly app: AppCompat, readonly _delegate: Messaging) {\n this.app = app;\n this._delegate = _delegate;\n }\n\n async getToken(options?: {\n vapidKey?: string;\n serviceWorkerRegistration?: ServiceWorkerRegistration;\n }): Promise<string> {\n return getToken(this._delegate, options);\n }\n\n async deleteToken(): Promise<boolean> {\n return deleteToken(this._delegate);\n }\n\n onMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe {\n return onMessage(this._delegate, nextOrObserver);\n }\n\n onBackgroundMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe {\n return onBackgroundMessage(this._delegate, nextOrObserver);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport { MessagingCompatImpl, isSupported } from './messaging-compat';\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'messaging-compat': MessagingCompatImpl;\n }\n}\n\nconst messagingCompatFactory: InstanceFactory<'messaging-compat'> = (\n container: ComponentContainer\n) => {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // in sw\n return new MessagingCompatImpl(\n container.getProvider('app-compat').getImmediate(),\n container.getProvider('messaging-sw').getImmediate()\n );\n } else {\n // in window\n return new MessagingCompatImpl(\n container.getProvider('app-compat').getImmediate(),\n container.getProvider('messaging').getImmediate()\n );\n }\n};\n\nconst NAMESPACE_EXPORTS = {\n isSupported\n};\n\nexport function registerMessagingCompat(): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'messaging-compat',\n messagingCompatFactory,\n ComponentType.PUBLIC\n ).setServiceProps(NAMESPACE_EXPORTS)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { name, version } from '../package.json';\n\nimport firebase from '@firebase/app-compat';\nimport { registerMessagingCompat } from './registerMessagingCompat';\nimport { MessagingCompat } from './messaging-compat';\n\nregisterMessagingCompat();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerMessaging`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n messaging: {\n (app?: FirebaseApp): MessagingCompat;\n isSupported(): boolean;\n };\n }\n interface FirebaseApp {\n messaging(): MessagingCompat;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Constants used in the Firebase Storage library.\n */\n\n/**\n * Domain name for firebase storage.\n */\nexport const DEFAULT_HOST = 'firebasestorage.googleapis.com';\n\n/**\n * The key in Firebase config json for the storage bucket.\n */\nexport const CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\n\n/**\n * 2 minutes\n *\n * The timeout for all operations except upload.\n */\nexport const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\n\n/**\n * 10 minutes\n *\n * The timeout for upload.\n */\nexport const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;\n\n/**\n * 1 second\n */\nexport const DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;\n\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport const MIN_SAFE_INTEGER = -9007199254740991;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { CONFIG_STORAGE_BUCKET_KEY } from './constants';\n\n/**\n * An error returned by the Firebase Storage SDK.\n * @public\n */\nexport class StorageError extends FirebaseError {\n private readonly _baseMessage: string;\n /**\n * Stores custom error data unque to StorageError.\n */\n customData: { serverResponse: string | null } = { serverResponse: null };\n\n /**\n * @param code - A StorageErrorCode string to be prefixed with 'storage/' and\n * added to the end of the message.\n * @param message - Error message.\n * @param status_ - Corresponding HTTP Status Code\n */\n constructor(code: StorageErrorCode, message: string, private status_ = 0) {\n super(\n prependCode(code),\n `Firebase Storage: ${message} (${prependCode(code)})`\n );\n this._baseMessage = this.message;\n // Without this, `instanceof StorageError`, in tests for example,\n // returns false.\n Object.setPrototypeOf(this, StorageError.prototype);\n }\n\n get status(): number {\n return this.status_;\n }\n\n set status(status: number) {\n this.status_ = status;\n }\n\n /**\n * Compares a StorageErrorCode against this error's code, filtering out the prefix.\n */\n _codeEquals(code: StorageErrorCode): boolean {\n return prependCode(code) === this.code;\n }\n\n /**\n * Optional response message that was added by the server.\n */\n get serverResponse(): null | string {\n return this.customData.serverResponse;\n }\n\n set serverResponse(serverResponse: string | null) {\n this.customData.serverResponse = serverResponse;\n if (this.customData.serverResponse) {\n this.message = `${this._baseMessage}\\n${this.customData.serverResponse}`;\n } else {\n this.message = this._baseMessage;\n }\n }\n}\n\nexport const errors = {};\n\n/**\n * @public\n * Error codes that can be attached to `StorageError`s.\n */\nexport const enum StorageErrorCode {\n // Shared between all platforms\n UNKNOWN = 'unknown',\n OBJECT_NOT_FOUND = 'object-not-found',\n BUCKET_NOT_FOUND = 'bucket-not-found',\n PROJECT_NOT_FOUND = 'project-not-found',\n QUOTA_EXCEEDED = 'quota-exceeded',\n UNAUTHENTICATED = 'unauthenticated',\n UNAUTHORIZED = 'unauthorized',\n UNAUTHORIZED_APP = 'unauthorized-app',\n RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded',\n INVALID_CHECKSUM = 'invalid-checksum',\n CANCELED = 'canceled',\n // JS specific\n INVALID_EVENT_NAME = 'invalid-event-name',\n INVALID_URL = 'invalid-url',\n INVALID_DEFAULT_BUCKET = 'invalid-default-bucket',\n NO_DEFAULT_BUCKET = 'no-default-bucket',\n CANNOT_SLICE_BLOB = 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size',\n NO_DOWNLOAD_URL = 'no-download-url',\n INVALID_ARGUMENT = 'invalid-argument',\n INVALID_ARGUMENT_COUNT = 'invalid-argument-count',\n APP_DELETED = 'app-deleted',\n INVALID_ROOT_OPERATION = 'invalid-root-operation',\n INVALID_FORMAT = 'invalid-format',\n INTERNAL_ERROR = 'internal-error',\n UNSUPPORTED_ENVIRONMENT = 'unsupported-environment'\n}\n\nexport function prependCode(code: StorageErrorCode): string {\n return 'storage/' + code;\n}\n\nexport function unknown(): StorageError {\n const message =\n 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new StorageError(StorageErrorCode.UNKNOWN, message);\n}\n\nexport function objectNotFound(path: string): StorageError {\n return new StorageError(\n StorageErrorCode.OBJECT_NOT_FOUND,\n \"Object '\" + path + \"' does not exist.\"\n );\n}\n\nexport function bucketNotFound(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.BUCKET_NOT_FOUND,\n \"Bucket '\" + bucket + \"' does not exist.\"\n );\n}\n\nexport function projectNotFound(project: string): StorageError {\n return new StorageError(\n StorageErrorCode.PROJECT_NOT_FOUND,\n \"Project '\" + project + \"' does not exist.\"\n );\n}\n\nexport function quotaExceeded(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.QUOTA_EXCEEDED,\n \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.'\n );\n}\n\nexport function unauthenticated(): StorageError {\n const message =\n 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);\n}\n\nexport function unauthorizedApp(): StorageError {\n return new StorageError(\n StorageErrorCode.UNAUTHORIZED_APP,\n 'This app does not have permission to access Firebase Storage on this project.'\n );\n}\n\nexport function unauthorized(path: string): StorageError {\n return new StorageError(\n StorageErrorCode.UNAUTHORIZED,\n \"User does not have permission to access '\" + path + \"'.\"\n );\n}\n\nexport function retryLimitExceeded(): StorageError {\n return new StorageError(\n StorageErrorCode.RETRY_LIMIT_EXCEEDED,\n 'Max retry time for operation exceeded, please try again.'\n );\n}\n\nexport function invalidChecksum(\n path: string,\n checksum: string,\n calculated: string\n): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_CHECKSUM,\n \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\"\n );\n}\n\nexport function canceled(): StorageError {\n return new StorageError(\n StorageErrorCode.CANCELED,\n 'User canceled the upload/download.'\n );\n}\n\nexport function invalidEventName(name: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_EVENT_NAME,\n \"Invalid event name '\" + name + \"'.\"\n );\n}\n\nexport function invalidUrl(url: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_URL,\n \"Invalid URL '\" + url + \"'.\"\n );\n}\n\nexport function invalidDefaultBucket(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_DEFAULT_BUCKET,\n \"Invalid default bucket '\" + bucket + \"'.\"\n );\n}\n\nexport function noDefaultBucket(): StorageError {\n return new StorageError(\n StorageErrorCode.NO_DEFAULT_BUCKET,\n 'No default bucket ' +\n \"found. Did you set the '\" +\n CONFIG_STORAGE_BUCKET_KEY +\n \"' property when initializing the app?\"\n );\n}\n\nexport function cannotSliceBlob(): StorageError {\n return new StorageError(\n StorageErrorCode.CANNOT_SLICE_BLOB,\n 'Cannot slice blob for upload. Please retry the upload.'\n );\n}\n\nexport function serverFileWrongSize(): StorageError {\n return new StorageError(\n StorageErrorCode.SERVER_FILE_WRONG_SIZE,\n 'Server recorded incorrect upload file size, please retry the upload.'\n );\n}\n\nexport function noDownloadURL(): StorageError {\n return new StorageError(\n StorageErrorCode.NO_DOWNLOAD_URL,\n 'The given file does not have any download URLs.'\n );\n}\n\nexport function missingPolyFill(polyFill: string): StorageError {\n return new StorageError(\n StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`\n );\n}\n\n/**\n * @internal\n */\nexport function invalidArgument(message: string): StorageError {\n return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);\n}\n\nexport function invalidArgumentCount(\n argMin: number,\n argMax: number,\n fnName: string,\n real: number\n): StorageError {\n let countPart;\n let plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n } else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new StorageError(\n StorageErrorCode.INVALID_ARGUMENT_COUNT,\n 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.'\n );\n}\n\nexport function appDeleted(): StorageError {\n return new StorageError(\n StorageErrorCode.APP_DELETED,\n 'The Firebase app was deleted.'\n );\n}\n\n/**\n * @param name - The name of the operation that was invalid.\n *\n * @internal\n */\nexport function invalidRootOperation(name: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_ROOT_OPERATION,\n \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\"\n );\n}\n\n/**\n * @param format - The format that was not valid.\n * @param message - A message describing the format violation.\n */\nexport function invalidFormat(format: string, message: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_FORMAT,\n \"String does not match format '\" + format + \"': \" + message\n );\n}\n\n/**\n * @param message - A message describing the internal error.\n */\nexport function unsupportedEnvironment(message: string): StorageError {\n throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, message);\n}\n\n/**\n * @param message - A message describing the internal error.\n */\nexport function internalError(message: string): StorageError {\n throw new StorageError(\n StorageErrorCode.INTERNAL_ERROR,\n 'Internal error: ' + message\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\nimport { invalidDefaultBucket, invalidUrl } from './error';\nimport { DEFAULT_HOST } from './constants';\n\n/**\n * Firebase Storage location data.\n *\n * @internal\n */\nexport class Location {\n private path_: string;\n\n constructor(public readonly bucket: string, path: string) {\n this.path_ = path;\n }\n\n get path(): string {\n return this.path_;\n }\n\n get isRoot(): boolean {\n return this.path.length === 0;\n }\n\n fullServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n }\n\n bucketOnlyServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n }\n\n static makeFromBucketSpec(bucketString: string, host: string): Location {\n let bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString, host);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw invalidDefaultBucket(bucketString);\n }\n }\n\n static makeFromUrl(url: string, host: string): Location {\n let location: Location | null = null;\n const bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\n\n function gsModify(loc: Location): void {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n const gsPath = '(/(.*))?$';\n const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n const gsIndices = { bucket: 1, path: 3 };\n\n function httpModify(loc: Location): void {\n loc.path_ = decodeURIComponent(loc.path);\n }\n const version = 'v[A-Za-z0-9_]+';\n const firebaseStorageHost = host.replace(/[.]/g, '\\\\.');\n const firebaseStoragePath = '(/([^?#]*).*)?$';\n const firebaseStorageRegExp = new RegExp(\n `^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`,\n 'i'\n );\n const firebaseStorageIndices = { bucket: 1, path: 3 };\n\n const cloudStorageHost =\n host === DEFAULT_HOST\n ? '(?:storage.googleapis.com|storage.cloud.google.com)'\n : host;\n const cloudStoragePath = '([^?#]*)';\n const cloudStorageRegExp = new RegExp(\n `^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`,\n 'i'\n );\n const cloudStorageIndices = { bucket: 1, path: 2 };\n\n const groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n {\n regex: firebaseStorageRegExp,\n indices: firebaseStorageIndices,\n postModify: httpModify\n },\n {\n regex: cloudStorageRegExp,\n indices: cloudStorageIndices,\n postModify: httpModify\n }\n ];\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n const captures = group.regex.exec(url);\n if (captures) {\n const bucketValue = captures[group.indices.bucket];\n let pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { StorageError } from './error';\nimport { Request } from './request';\n\n/**\n * A request whose promise always fails.\n */\nexport class FailRequest<T> implements Request<T> {\n promise_: Promise<T>;\n\n constructor(error: StorageError) {\n this.promise_ = Promise.reject<T>(error);\n }\n\n /** @inheritDoc */\n getPromise(): Promise<T> {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(_appDelete = false): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isNode } from '@firebase/util';\nimport { invalidArgument } from './error';\n\nexport function isJustDef<T>(p: T | null | undefined): p is T | null {\n return p !== void 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isFunction(p: unknown): p is Function {\n return typeof p === 'function';\n}\n\nexport function isNonArrayObject(p: unknown): boolean {\n return typeof p === 'object' && !Array.isArray(p);\n}\n\nexport function isString(p: unknown): p is string {\n return typeof p === 'string' || p instanceof String;\n}\n\nexport function isNativeBlob(p: unknown): p is Blob {\n return isNativeBlobDefined() && p instanceof Blob;\n}\n\nexport function isNativeBlobDefined(): boolean {\n // Note: The `isNode()` check can be removed when `node-fetch` adds native Blob support\n // PR: https://github.com/node-fetch/node-fetch/pull/1664\n return typeof Blob !== 'undefined' && !isNode();\n}\n\nexport function validateNumber(\n argument: string,\n minValue: number,\n maxValue: number,\n value: number\n): void {\n if (value < minValue) {\n throw invalidArgument(\n `Invalid value for '${argument}'. Expected ${minValue} or greater.`\n );\n }\n if (value > maxValue) {\n throw invalidArgument(\n `Invalid value for '${argument}'. Expected ${maxValue} or less.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport { UrlParams } from './requestinfo';\n\nexport function makeUrl(\n urlPart: string,\n host: string,\n protocol: string\n): string {\n let origin = host;\n if (protocol == null) {\n origin = `https://${host}`;\n }\n return `${protocol}://${origin}/v0${urlPart}`;\n}\n\nexport function makeQueryString(params: UrlParams): string {\n const encode = encodeURIComponent;\n let queryPart = '?';\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n const nextPart = encode(key) + '=' + encode(params[key]);\n queryPart = queryPart + nextPart + '&';\n }\n }\n\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks the status code to see if the action should be retried.\n *\n * @param status Current HTTP status code returned by server.\n * @param additionalRetryCodes additional retry codes to check against\n */\nexport function isRetryStatusCode(\n status: number,\n additionalRetryCodes: number[]\n): boolean {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n const isFiveHundredCode = status >= 500 && status < 600;\n const extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;\n const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;\n return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\nimport { id as backoffId, start, stop } from './backoff';\nimport { appDeleted, canceled, retryLimitExceeded, unknown } from './error';\nimport { ErrorHandler, RequestHandler, RequestInfo } from './requestinfo';\nimport { isJustDef } from './type';\nimport { makeQueryString } from './url';\nimport { Connection, ErrorCode, Headers, ConnectionType } from './connection';\nimport { isRetryStatusCode } from './utils';\n\nexport interface Request<T> {\n getPromise(): Promise<T>;\n\n /**\n * Cancels the request. IMPORTANT: the promise may still be resolved with an\n * appropriate value (if the request is finished before you call this method,\n * but the promise has not yet been resolved), so don't just assume it will be\n * rejected if you call this function.\n * @param appDelete - True if the cancelation came from the app being deleted.\n */\n cancel(appDelete?: boolean): void;\n}\n\n/**\n * Handles network logic for all Storage Requests, including error reporting and\n * retries with backoff.\n *\n * @param I - the type of the backend's network response.\n * @param - O the output type used by the rest of the SDK. The conversion\n * happens in the specified `callback_`.\n */\nclass NetworkRequest<I extends ConnectionType, O> implements Request<O> {\n private pendingConnection_: Connection<I> | null = null;\n private backoffId_: backoffId | null = null;\n private resolve_!: (value?: O | PromiseLike<O>) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private reject_!: (reason?: any) => void;\n private canceled_: boolean = false;\n private appDelete_: boolean = false;\n private promise_: Promise<O>;\n\n constructor(\n private url_: string,\n private method_: string,\n private headers_: Headers,\n private body_: string | Blob | Uint8Array | null,\n private successCodes_: number[],\n private additionalRetryCodes_: number[],\n private callback_: RequestHandler<I, O>,\n private errorCallback_: ErrorHandler | null,\n private timeout_: number,\n private progressCallback_: ((p1: number, p2: number) => void) | null,\n private connectionFactory_: () => Connection<I>,\n private retry = true\n ) {\n this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve as (value?: O | PromiseLike<O>) => void;\n this.reject_ = reject;\n this.start_();\n });\n }\n\n /**\n * Actually starts the retry loop.\n */\n private start_(): void {\n const doTheRequest: (\n backoffCallback: (success: boolean, ...p2: unknown[]) => void,\n canceled: boolean\n ) => void = (backoffCallback, canceled) => {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n const connection = this.connectionFactory_();\n this.pendingConnection_ = connection;\n\n const progressListener: (\n progressEvent: ProgressEvent\n ) => void = progressEvent => {\n const loaded = progressEvent.loaded;\n const total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (this.progressCallback_ !== null) {\n this.progressCallback_(loaded, total);\n }\n };\n if (this.progressCallback_ !== null) {\n connection.addUploadProgressListener(progressListener);\n }\n\n // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n connection\n .send(this.url_, this.method_, this.body_, this.headers_)\n .then(() => {\n if (this.progressCallback_ !== null) {\n connection.removeUploadProgressListener(progressListener);\n }\n this.pendingConnection_ = null;\n const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;\n const status = connection.getStatus();\n if (\n !hitServer ||\n (isRetryStatusCode(status, this.additionalRetryCodes_) &&\n this.retry)\n ) {\n const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(\n false,\n new RequestEndStatus(false, null, wasCanceled)\n );\n return;\n }\n const successCode = this.successCodes_.indexOf(status) !== -1;\n backoffCallback(true, new RequestEndStatus(successCode, connection));\n });\n };\n\n /**\n * @param requestWentThrough - True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n const backoffDone: (\n requestWentThrough: boolean,\n status: RequestEndStatus<I>\n ) => void = (requestWentThrough, status) => {\n const resolve = this.resolve_;\n const reject = this.reject_;\n const connection = status.connection as Connection<I>;\n if (status.wasSuccessCode) {\n try {\n const result = this.callback_(connection, connection.getResponse());\n if (isJustDef(result)) {\n resolve(result);\n } else {\n resolve();\n }\n } catch (e) {\n reject(e);\n }\n } else {\n if (connection !== null) {\n const err = unknown();\n err.serverResponse = connection.getErrorText();\n if (this.errorCallback_) {\n reject(this.errorCallback_(connection, err));\n } else {\n reject(err);\n }\n } else {\n if (status.canceled) {\n const err = this.appDelete_ ? appDeleted() : canceled();\n reject(err);\n } else {\n const err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n };\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n } else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n }\n\n /** @inheritDoc */\n getPromise(): Promise<O> {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(appDelete?: boolean): void {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingConnection_ !== null) {\n this.pendingConnection_.abort();\n }\n }\n}\n\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled - Defaults to false.\n */\nexport class RequestEndStatus<I extends ConnectionType> {\n /**\n * True if the request was canceled.\n */\n canceled: boolean;\n\n constructor(\n public wasSuccessCode: boolean,\n public connection: Connection<I> | null,\n canceled?: boolean\n ) {\n this.canceled = !!canceled;\n }\n}\n\nexport function addAuthHeader_(\n headers: Headers,\n authToken: string | null\n): void {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\n\nexport function addVersionHeader_(\n headers: Headers,\n firebaseVersion?: string\n): void {\n headers['X-Firebase-Storage-Version'] =\n 'webjs/' + (firebaseVersion ?? 'AppManager');\n}\n\nexport function addGmpidHeader_(headers: Headers, appId: string | null): void {\n if (appId) {\n headers['X-Firebase-GMPID'] = appId;\n }\n}\n\nexport function addAppCheckHeader_(\n headers: Headers,\n appCheckToken: string | null\n): void {\n if (appCheckToken !== null) {\n headers['X-Firebase-AppCheck'] = appCheckToken;\n }\n}\n\nexport function makeRequest<I extends ConnectionType, O>(\n requestInfo: RequestInfo<I, O>,\n appId: string | null,\n authToken: string | null,\n appCheckToken: string | null,\n requestFactory: () => Connection<I>,\n firebaseVersion?: string,\n retry = true\n): Request<O> {\n const queryPart = makeQueryString(requestInfo.urlParams);\n const url = requestInfo.url + queryPart;\n const headers = Object.assign({}, requestInfo.headers);\n addGmpidHeader_(headers, appId);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers, firebaseVersion);\n addAppCheckHeader_(headers, appCheckToken);\n return new NetworkRequest<I, O>(\n url,\n requestInfo.method,\n headers,\n requestInfo.body,\n requestInfo.successCodes,\n requestInfo.additionalRetryCodes,\n requestInfo.handler,\n requestInfo.errorHandler,\n requestInfo.timeout,\n requestInfo.progressCallback,\n requestFactory,\n retry\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Provides a method for running a function with exponential\n * backoff.\n */\ntype id = (p1: boolean) => void;\n\nexport { id };\n\n/**\n * Accepts a callback for an action to perform (`doRequest`),\n * and then a callback for when the backoff has completed (`backoffCompleteCb`).\n * The callback sent to start requires an argument to call (`onRequestComplete`).\n * When `start` calls `doRequest`, it passes a callback for when the request has\n * completed, `onRequestComplete`. Based on this, the backoff continues, with\n * another call to `doRequest` and the above loop continues until the timeout\n * is hit, or a successful response occurs.\n * @description\n * @param doRequest Callback to perform request\n * @param backoffCompleteCb Callback to call when backoff has been completed\n */\nexport function start(\n doRequest: (\n onRequestComplete: (success: boolean) => void,\n canceled: boolean\n ) => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n backoffCompleteCb: (...args: any[]) => unknown,\n timeout: number\n): id {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n let waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n // TODO: find a way to exclude Node type definition for storage because storage only works in browser\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let retryTimeoutId: any = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let globalTimeoutId: any = null;\n let hitTimeout = false;\n let cancelState = 0;\n\n function canceled(): boolean {\n return cancelState === 2;\n }\n let triggeredCallback = false;\n\n function triggerCallback(...args: any[]): void {\n if (!triggeredCallback) {\n triggeredCallback = true;\n backoffCompleteCb.apply(null, args);\n }\n }\n\n function callWithDelay(millis: number): void {\n retryTimeoutId = setTimeout(() => {\n retryTimeoutId = null;\n doRequest(responseHandler, canceled());\n }, millis);\n }\n\n function clearGlobalTimeout(): void {\n if (globalTimeoutId) {\n clearTimeout(globalTimeoutId);\n }\n }\n\n function responseHandler(success: boolean, ...args: any[]): void {\n if (triggeredCallback) {\n clearGlobalTimeout();\n return;\n }\n if (success) {\n clearGlobalTimeout();\n triggerCallback.call(null, success, ...args);\n return;\n }\n const mustStop = canceled() || hitTimeout;\n if (mustStop) {\n clearGlobalTimeout();\n triggerCallback.call(null, success, ...args);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n let waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n } else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n let stopped = false;\n\n function stop(wasTimeout: boolean): void {\n if (stopped) {\n return;\n }\n stopped = true;\n clearGlobalTimeout();\n if (triggeredCallback) {\n return;\n }\n if (retryTimeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(retryTimeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n globalTimeoutId = setTimeout(() => {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id: id): void {\n id(false);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Some methods copied from goog.fs.\n * We don't include goog.fs because it pulls in a bunch of Deferred code that\n * bloats the size of the released binary.\n */\nimport { isNativeBlobDefined } from './type';\nimport { StorageErrorCode, StorageError } from './error';\n\nfunction getBlobBuilder(): typeof IBlobBuilder | undefined {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n } else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n } else {\n return undefined;\n }\n}\n\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob(...args: Array<string | Blob | ArrayBuffer>): Blob {\n const BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n const bb = new BlobBuilder();\n for (let i = 0; i < args.length; i++) {\n bb.append(args[i]);\n }\n return bb.getBlob();\n } else {\n if (isNativeBlobDefined()) {\n return new Blob(args);\n } else {\n throw new StorageError(\n StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n \"This browser doesn't seem to support creating Blobs\"\n );\n }\n }\n}\n\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob: Blob, start: number, end: number): Blob | null {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n } else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n } else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { missingPolyFill } from '../../implementation/error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n if (typeof atob === 'undefined') {\n throw missingPolyFill('base-64');\n }\n return atob(encoded);\n}\n\nexport function decodeUint8Array(data: Uint8Array): string {\n return new TextDecoder().decode(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { unknown, invalidFormat } from './error';\nimport { decodeBase64 } from '../platform/base64';\n\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport type StringFormat = typeof StringFormat[keyof typeof StringFormat];\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport const StringFormat = {\n /**\n * Indicates the string should be interpreted \"raw\", that is, as normal text.\n * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte\n * sequence.\n * Example: The string 'Hello! \\\\ud83d\\\\ude0a' becomes the byte sequence\n * 48 65 6c 6c 6f 21 20 f0 9f 98 8a\n */\n RAW: 'raw',\n /**\n * Indicates the string should be interpreted as base64-encoded data.\n * Padding characters (trailing '='s) are optional.\n * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence\n * ad 69 8e fb e1 3a b7 bf eb 97\n */\n BASE64: 'base64',\n /**\n * Indicates the string should be interpreted as base64url-encoded data.\n * Padding characters (trailing '='s) are optional.\n * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence\n * ad 69 8e fb e1 3a b7 bf eb 97\n */\n BASE64URL: 'base64url',\n /**\n * Indicates the string is a data URL, such as one obtained from\n * canvas.toDataURL().\n * Example: the string 'data:application/octet-stream;base64,aaaa'\n * becomes the byte sequence\n * 69 a6 9a\n * (the content-type \"application/octet-stream\" is also applied, but can\n * be overridden in the metadata object).\n */\n DATA_URL: 'data_url'\n} as const;\n\nexport class StringData {\n contentType: string | null;\n\n constructor(public data: Uint8Array, contentType?: string | null) {\n this.contentType = contentType || null;\n }\n}\n\n/**\n * @internal\n */\nexport function dataFromString(\n format: StringFormat,\n stringData: string\n): StringData {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(stringData));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, stringData));\n case StringFormat.DATA_URL:\n return new StringData(\n dataURLBytes_(stringData),\n dataURLContentType_(stringData)\n );\n default:\n // do nothing\n }\n\n // assert(false);\n throw unknown();\n}\n\nexport function utf8Bytes_(value: string): Uint8Array {\n const b: number[] = [];\n for (let i = 0; i < value.length; i++) {\n let c = value.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n } else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n } else {\n if ((c & 64512) === 55296) {\n // The start of a surrogate pair.\n const valid =\n i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n const hi = c;\n const lo = value.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(\n 240 | (c >> 18),\n 128 | ((c >> 12) & 63),\n 128 | ((c >> 6) & 63),\n 128 | (c & 63)\n );\n }\n } else {\n if ((c & 64512) === 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n } else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\n\nexport function percentEncodedBytes_(value: string): Uint8Array {\n let decoded;\n try {\n decoded = decodeURIComponent(value);\n } catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\n\nexport function base64Bytes_(format: StringFormat, value: string): Uint8Array {\n switch (format) {\n case StringFormat.BASE64: {\n const hasMinus = value.indexOf('-') !== -1;\n const hasUnder = value.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n const invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(\n format,\n \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\"\n );\n }\n break;\n }\n case StringFormat.BASE64URL: {\n const hasPlus = value.indexOf('+') !== -1;\n const hasSlash = value.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n const invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(\n format,\n \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\"\n );\n }\n value = value.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n default:\n // do nothing\n }\n let bytes;\n try {\n bytes = decodeBase64(value);\n } catch (e) {\n if ((e as Error).message.includes('polyfill')) {\n throw e;\n }\n throw invalidFormat(format, 'Invalid character found');\n }\n const array = new Uint8Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n\nclass DataURLParts {\n base64: boolean = false;\n contentType: string | null = null;\n rest: string;\n\n constructor(dataURL: string) {\n const matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(\n StringFormat.DATA_URL,\n \"Must be formatted 'data:[<mediatype>][;base64],<data>\"\n );\n }\n const middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n}\n\nexport function dataURLBytes_(dataUrl: string): Uint8Array {\n const parts = new DataURLParts(dataUrl);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\n\nexport function dataURLContentType_(dataUrl: string): string | null {\n const parts = new DataURLParts(dataUrl);\n return parts.contentType;\n}\n\nfunction endsWith(s: string, end: string): boolean {\n const longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n\n return s.substring(s.length - end.length) === end;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport { sliceBlob, getBlob } from './fs';\nimport { StringFormat, dataFromString } from './string';\nimport { isNativeBlob, isNativeBlobDefined, isString } from './type';\n\n/**\n * @param opt_elideCopy - If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n *\n * @internal\n */\nexport class FbsBlob {\n private data_!: Blob | Uint8Array;\n private size_: number;\n private type_: string;\n\n constructor(data: Blob | Uint8Array | ArrayBuffer, elideCopy?: boolean) {\n let size: number = 0;\n let blobType: string = '';\n if (isNativeBlob(data)) {\n this.data_ = data as Blob;\n size = (data as Blob).size;\n blobType = (data as Blob).type;\n } else if (data instanceof ArrayBuffer) {\n if (elideCopy) {\n this.data_ = new Uint8Array(data);\n } else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n } else if (data instanceof Uint8Array) {\n if (elideCopy) {\n this.data_ = data as Uint8Array;\n } else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data as Uint8Array);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n\n size(): number {\n return this.size_;\n }\n\n type(): string {\n return this.type_;\n }\n\n slice(startByte: number, endByte: number): FbsBlob | null {\n if (isNativeBlob(this.data_)) {\n const realBlob = this.data_ as Blob;\n const sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n } else {\n const slice = new Uint8Array(\n (this.data_ as Uint8Array).buffer,\n startByte,\n endByte - startByte\n );\n return new FbsBlob(slice, true);\n }\n }\n\n static getBlob(...args: Array<string | FbsBlob>): FbsBlob | null {\n if (isNativeBlobDefined()) {\n const blobby: Array<Blob | Uint8Array | string> = args.map(\n (val: string | FbsBlob): Blob | Uint8Array | string => {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n }\n );\n return new FbsBlob(getBlob.apply(null, blobby));\n } else {\n const uint8Arrays: Uint8Array[] = args.map(\n (val: string | FbsBlob): Uint8Array => {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val as string).data;\n } else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return (val as FbsBlob).data_ as Uint8Array;\n }\n }\n );\n let finalLength = 0;\n uint8Arrays.forEach((array: Uint8Array): void => {\n finalLength += array.byteLength;\n });\n const merged = new Uint8Array(finalLength);\n let index = 0;\n uint8Arrays.forEach((array: Uint8Array) => {\n for (let i = 0; i < array.length; i++) {\n merged[index++] = array[i];\n }\n });\n return new FbsBlob(merged, true);\n }\n }\n\n uploadData(): Blob | Uint8Array {\n return this.data_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { isNonArrayObject } from './type';\n\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(\n s: string\n): { [name: string]: unknown } | null {\n let obj;\n try {\n obj = JSON.parse(s);\n } catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Contains helper methods for manipulating paths.\n */\n\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path: string): string | null {\n if (path.length === 0) {\n return null;\n }\n const index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n const newPath = path.slice(0, index);\n return newPath;\n}\n\nexport function child(path: string, childPath: string): string {\n const canonicalChildPath = childPath\n .split('/')\n .filter(component => component.length > 0)\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n } else {\n return path + '/' + canonicalChildPath;\n }\n}\n\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path: string): string {\n const index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n } else {\n return path.slice(index + 1);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the metadata format\n */\nimport { Metadata } from '../metadata';\n\nimport { jsonObjectOrNull } from './json';\nimport { Location } from './location';\nimport { lastComponent } from './path';\nimport { isString } from './type';\nimport { makeUrl, makeQueryString } from './url';\nimport { Reference } from '../reference';\nimport { FirebaseStorageImpl } from '../service';\n\nexport function noXform_<T>(metadata: Metadata, value: T): T {\n return value;\n}\n\nclass Mapping<T> {\n local: string;\n writable: boolean;\n xform: (p1: Metadata, p2?: T) => T | undefined;\n\n constructor(\n public server: string,\n local?: string | null,\n writable?: boolean,\n xform?: ((p1: Metadata, p2?: T) => T | undefined) | null\n ) {\n this.local = local || server;\n this.writable = !!writable;\n this.xform = xform || noXform_;\n }\n}\ntype Mappings = Array<Mapping<string> | Mapping<number>>;\n\nexport { Mappings };\n\nlet mappings_: Mappings | null = null;\n\nexport function xformPath(fullPath: string | undefined): string | undefined {\n if (!isString(fullPath) || fullPath.length < 2) {\n return fullPath;\n } else {\n return lastComponent(fullPath);\n }\n}\n\nexport function getMappings(): Mappings {\n if (mappings_) {\n return mappings_;\n }\n const mappings: Mappings = [];\n mappings.push(new Mapping<string>('bucket'));\n mappings.push(new Mapping<string>('generation'));\n mappings.push(new Mapping<string>('metageneration'));\n mappings.push(new Mapping<string>('name', 'fullPath', true));\n\n function mappingsXformPath(\n _metadata: Metadata,\n fullPath: string | undefined\n ): string | undefined {\n return xformPath(fullPath);\n }\n const nameMapping = new Mapping<string>('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(\n _metadata: Metadata,\n size?: number | string\n ): number | undefined {\n if (size !== undefined) {\n return Number(size);\n } else {\n return size;\n }\n }\n const sizeMapping = new Mapping<number>('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping<number>('timeCreated'));\n mappings.push(new Mapping<string>('updated'));\n mappings.push(new Mapping<string>('md5Hash', null, true));\n mappings.push(new Mapping<string>('cacheControl', null, true));\n mappings.push(new Mapping<string>('contentDisposition', null, true));\n mappings.push(new Mapping<string>('contentEncoding', null, true));\n mappings.push(new Mapping<string>('contentLanguage', null, true));\n mappings.push(new Mapping<string>('contentType', null, true));\n mappings.push(new Mapping<string>('metadata', 'customMetadata', true));\n mappings_ = mappings;\n return mappings_;\n}\n\nexport function addRef(metadata: Metadata, service: FirebaseStorageImpl): void {\n function generateRef(): Reference {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const loc = new Location(bucket, path);\n return service._makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\n\nexport function fromResource(\n service: FirebaseStorageImpl,\n resource: { [name: string]: unknown },\n mappings: Mappings\n): Metadata {\n const metadata: Metadata = {} as Metadata;\n metadata['type'] = 'file';\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n metadata[mapping.local] = (mapping as Mapping<unknown>).xform(\n metadata,\n resource[mapping.server]\n );\n }\n addRef(metadata, service);\n return metadata;\n}\n\nexport function fromResourceString(\n service: FirebaseStorageImpl,\n resourceString: string,\n mappings: Mappings\n): Metadata | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as Metadata;\n return fromResource(service, resource, mappings);\n}\n\nexport function downloadUrlFromResourceString(\n metadata: Metadata,\n resourceString: string,\n host: string,\n protocol: string\n): string | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n if (!isString(obj['downloadTokens'])) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return null;\n }\n const tokens: string = obj['downloadTokens'] as string;\n if (tokens.length === 0) {\n return null;\n }\n const encode = encodeURIComponent;\n const tokensList = tokens.split(',');\n const urls = tokensList.map((token: string): string => {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n const base = makeUrl(urlPart, host, protocol);\n const queryString = makeQueryString({\n alt: 'media',\n token\n });\n return base + queryString;\n });\n return urls[0];\n}\n\nexport function toResourceString(\n metadata: Partial<Metadata>,\n mappings: Mappings\n): string {\n const resource: {\n [prop: string]: unknown;\n } = {};\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the listOptions and listResult format\n */\nimport { Location } from './location';\nimport { jsonObjectOrNull } from './json';\nimport { ListResult } from '../list';\nimport { FirebaseStorageImpl } from '../service';\n\n/**\n * Represents the simplified object metadata returned by List API.\n * Other fields are filtered because list in Firebase Rules does not grant\n * the permission to read the metadata.\n */\ninterface ListMetadataResponse {\n name: string;\n bucket: string;\n}\n\n/**\n * Represents the JSON response of List API.\n */\ninterface ListResultResponse {\n prefixes: string[];\n items: ListMetadataResponse[];\n nextPageToken?: string;\n}\n\nconst PREFIXES_KEY = 'prefixes';\nconst ITEMS_KEY = 'items';\n\nfunction fromBackendResponse(\n service: FirebaseStorageImpl,\n bucket: string,\n resource: ListResultResponse\n): ListResult {\n const listResult: ListResult = {\n prefixes: [],\n items: [],\n nextPageToken: resource['nextPageToken']\n };\n if (resource[PREFIXES_KEY]) {\n for (const path of resource[PREFIXES_KEY]) {\n const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\n const reference = service._makeStorageReference(\n new Location(bucket, pathWithoutTrailingSlash)\n );\n listResult.prefixes.push(reference);\n }\n }\n\n if (resource[ITEMS_KEY]) {\n for (const item of resource[ITEMS_KEY]) {\n const reference = service._makeStorageReference(\n new Location(bucket, item['name'])\n );\n listResult.items.push(reference);\n }\n }\n return listResult;\n}\n\nexport function fromResponseString(\n service: FirebaseStorageImpl,\n bucket: string,\n resourceString: string\n): ListResult | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as unknown as ListResultResponse;\n return fromBackendResponse(service, bucket, resource);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { StorageError } from './error';\nimport { Headers, Connection, ConnectionType } from './connection';\n\n/**\n * Type for url params stored in RequestInfo.\n */\nexport interface UrlParams {\n [name: string]: string | number;\n}\n\n/**\n * A function that converts a server response to the API type expected by the\n * SDK.\n *\n * @param I - the type of the backend's network response\n * @param O - the output response type used by the rest of the SDK.\n */\nexport type RequestHandler<I extends ConnectionType, O> = (\n connection: Connection<I>,\n response: I\n) => O;\n\n/** A function to handle an error. */\nexport type ErrorHandler = (\n connection: Connection<ConnectionType>,\n response: StorageError\n) => StorageError;\n\n/**\n * Contains a fully specified request.\n *\n * @param I - the type of the backend's network response.\n * @param O - the output response type used by the rest of the SDK.\n */\nexport class RequestInfo<I extends ConnectionType, O> {\n urlParams: UrlParams = {};\n headers: Headers = {};\n body: Blob | string | Uint8Array | null = null;\n errorHandler: ErrorHandler | null = null;\n\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n progressCallback: ((p1: number, p2: number) => void) | null = null;\n successCodes: number[] = [200];\n additionalRetryCodes: number[] = [];\n\n constructor(\n public url: string,\n public method: string,\n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n public handler: RequestHandler<I, O>,\n public timeout: number\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods for interacting with the network.\n */\n\nimport { Metadata } from '../metadata';\nimport { ListResult } from '../list';\nimport { FbsBlob } from './blob';\nimport {\n StorageError,\n cannotSliceBlob,\n unauthenticated,\n quotaExceeded,\n unauthorized,\n objectNotFound,\n serverFileWrongSize,\n unknown,\n unauthorizedApp\n} from './error';\nimport { Location } from './location';\nimport {\n Mappings,\n fromResourceString,\n downloadUrlFromResourceString,\n toResourceString\n} from './metadata';\nimport { fromResponseString } from './list';\nimport { RequestInfo, UrlParams } from './requestinfo';\nimport { isString } from './type';\nimport { makeUrl } from './url';\nimport { Connection, ConnectionType } from './connection';\nimport { FirebaseStorageImpl } from '../service';\n\n/**\n * Throws the UNKNOWN StorageError if cndn is false.\n */\nexport function handlerCheck(cndn: boolean): void {\n if (!cndn) {\n throw unknown();\n }\n}\n\nexport function metadataHandler(\n service: FirebaseStorageImpl,\n mappings: Mappings\n): (p1: Connection<string>, p2: string) => Metadata {\n function handler(xhr: Connection<string>, text: string): Metadata {\n const metadata = fromResourceString(service, text, mappings);\n handlerCheck(metadata !== null);\n return metadata as Metadata;\n }\n return handler;\n}\n\nexport function listHandler(\n service: FirebaseStorageImpl,\n bucket: string\n): (p1: Connection<string>, p2: string) => ListResult {\n function handler(xhr: Connection<string>, text: string): ListResult {\n const listResult = fromResponseString(service, bucket, text);\n handlerCheck(listResult !== null);\n return listResult as ListResult;\n }\n return handler;\n}\n\nexport function downloadUrlHandler(\n service: FirebaseStorageImpl,\n mappings: Mappings\n): (p1: Connection<string>, p2: string) => string | null {\n function handler(xhr: Connection<string>, text: string): string | null {\n const metadata = fromResourceString(service, text, mappings);\n handlerCheck(metadata !== null);\n return downloadUrlFromResourceString(\n metadata as Metadata,\n text,\n service.host,\n service._protocol\n );\n }\n return handler;\n}\n\nexport function sharedErrorHandler(\n location: Location\n): (p1: Connection<ConnectionType>, p2: StorageError) => StorageError {\n function errorHandler(\n xhr: Connection<ConnectionType>,\n err: StorageError\n ): StorageError {\n let newErr: StorageError;\n if (xhr.getStatus() === 401) {\n if (\n // This exact message string is the only consistent part of the\n // server's error response that identifies it as an App Check error.\n xhr.getErrorText().includes('Firebase App Check token is invalid')\n ) {\n newErr = unauthorizedApp();\n } else {\n newErr = unauthenticated();\n }\n } else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n } else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n } else {\n newErr = err;\n }\n }\n }\n newErr.status = xhr.getStatus();\n newErr.serverResponse = err.serverResponse;\n return newErr;\n }\n return errorHandler;\n}\n\nexport function objectErrorHandler(\n location: Location\n): (p1: Connection<ConnectionType>, p2: StorageError) => StorageError {\n const shared = sharedErrorHandler(location);\n\n function errorHandler(\n xhr: Connection<ConnectionType>,\n err: StorageError\n ): StorageError {\n let newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.serverResponse = err.serverResponse;\n return newErr;\n }\n return errorHandler;\n}\n\nexport function getMetadata(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings\n): RequestInfo<string, Metadata> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function list(\n service: FirebaseStorageImpl,\n location: Location,\n delimiter?: string,\n pageToken?: string | null,\n maxResults?: number | null\n): RequestInfo<string, ListResult> {\n const urlParams: UrlParams = {};\n if (location.isRoot) {\n urlParams['prefix'] = '';\n } else {\n urlParams['prefix'] = location.path + '/';\n }\n if (delimiter && delimiter.length > 0) {\n urlParams['delimiter'] = delimiter;\n }\n if (pageToken) {\n urlParams['pageToken'] = pageToken;\n }\n if (maxResults) {\n urlParams['maxResults'] = maxResults;\n }\n const urlPart = location.bucketOnlyServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n listHandler(service, location.bucket),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\nexport function getBytes<I extends ConnectionType>(\n service: FirebaseStorageImpl,\n location: Location,\n maxDownloadSizeBytes?: number\n): RequestInfo<I, I> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n (_: Connection<I>, data: I) => data,\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n if (maxDownloadSizeBytes !== undefined) {\n requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;\n requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];\n }\n return requestInfo;\n}\n\nexport function getDownloadUrl(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings\n): RequestInfo<string, string | null> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n downloadUrlHandler(service, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function updateMetadata(\n service: FirebaseStorageImpl,\n location: Location,\n metadata: Partial<Metadata>,\n mappings: Mappings\n): RequestInfo<string, Metadata> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'PATCH';\n const body = toResourceString(metadata, mappings);\n const headers = { 'Content-Type': 'application/json; charset=utf-8' };\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function deleteObject(\n service: FirebaseStorageImpl,\n location: Location\n): RequestInfo<string, void> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'DELETE';\n const timeout = service.maxOperationRetryTime;\n\n function handler(_xhr: Connection<string>, _text: string): void {}\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function determineContentType_(\n metadata: Metadata | null,\n blob: FbsBlob | null\n): string {\n return (\n (metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream'\n );\n}\n\nexport function metadataForUpload_(\n location: Location,\n blob: FbsBlob,\n metadata?: Metadata | null\n): Metadata {\n const metadataClone = Object.assign({}, metadata);\n metadataClone['fullPath'] = location.path;\n metadataClone['size'] = blob.size();\n if (!metadataClone['contentType']) {\n metadataClone['contentType'] = determineContentType_(null, blob);\n }\n return metadataClone;\n}\n\n/**\n * Prepare RequestInfo for uploads as Content-Type: multipart.\n */\nexport function multipartUpload(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<string, Metadata> {\n const urlPart = location.bucketOnlyServerUrl();\n const headers: { [prop: string]: string } = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n\n function genBoundary(): string {\n let str = '';\n for (let i = 0; i < 2; i++) {\n str = str + Math.random().toString().slice(2);\n }\n return str;\n }\n const boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n const metadata_ = metadataForUpload_(location, blob, metadata);\n const metadataString = toResourceString(metadata_, mappings);\n const preBlobPart =\n '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata_['contentType'] +\n '\\r\\n\\r\\n';\n const postBlobPart = '\\r\\n--' + boundary + '--';\n const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n const urlParams: UrlParams = { name: metadata_['fullPath']! };\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n */\nexport class ResumableUploadStatus {\n finalized: boolean;\n metadata: Metadata | null;\n\n constructor(\n public current: number,\n public total: number,\n finalized?: boolean,\n metadata?: Metadata | null\n ) {\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n}\n\nexport function checkResumeHeader_(\n xhr: Connection<string>,\n allowed?: string[]\n): string {\n let status: string | null = null;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n const allowedStatus = allowed || ['active'];\n handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);\n return status as string;\n}\n\nexport function createResumableUpload(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<string, string> {\n const urlPart = location.bucketOnlyServerUrl();\n const metadataForUpload = metadataForUpload_(location, blob, metadata);\n const urlParams: UrlParams = { name: metadataForUpload['fullPath']! };\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'POST';\n const headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${blob.size()}`,\n 'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType']!,\n 'Content-Type': 'application/json; charset=utf-8'\n };\n const body = toResourceString(metadataForUpload, mappings);\n const timeout = service.maxUploadRetryTime;\n\n function handler(xhr: Connection<string>): string {\n checkResumeHeader_(xhr);\n let url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url as string;\n }\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(\n service: FirebaseStorageImpl,\n location: Location,\n url: string,\n blob: FbsBlob\n): RequestInfo<string, ResumableUploadStatus> {\n const headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: Connection<string>): ResumableUploadStatus {\n const status = checkResumeHeader_(xhr, ['active', 'final']);\n let sizeString: string | null = null;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n\n if (!sizeString) {\n // null or empty string\n handlerCheck(false);\n }\n\n const size = Number(sizeString);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport const RESUMABLE_UPLOAD_CHUNK_SIZE: number = 256 * 1024;\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(\n location: Location,\n service: FirebaseStorageImpl,\n url: string,\n blob: FbsBlob,\n chunkSize: number,\n mappings: Mappings,\n status?: ResumableUploadStatus | null,\n progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo<string, ResumableUploadStatus> {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n const status_ = new ResumableUploadStatus(0, 0);\n if (status) {\n status_.current = status.current;\n status_.total = status.total;\n } else {\n status_.current = 0;\n status_.total = blob.size();\n }\n if (blob.size() !== status_.total) {\n throw serverFileWrongSize();\n }\n const bytesLeft = status_.total - status_.current;\n let bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n const startByte = status_.current;\n const endByte = startByte + bytesToUpload;\n let uploadCommand = '';\n if (bytesToUpload === 0) {\n uploadCommand = 'finalize';\n } else if (bytesLeft === bytesToUpload) {\n uploadCommand = 'upload, finalize';\n } else {\n uploadCommand = 'upload';\n }\n const headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': `${status_.current}`\n };\n const body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n\n function handler(\n xhr: Connection<string>,\n text: string\n ): ResumableUploadStatus {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n const newCurrent = status_.current + bytesToUpload;\n const size = blob.size();\n let metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(service, mappings)(xhr, text);\n } else {\n metadata = null;\n }\n return new ResumableUploadStatus(\n newCurrent,\n size,\n uploadStatus === 'final',\n metadata\n );\n }\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Enumerations used for upload tasks.\n */\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport type TaskEvent = string;\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport const TaskEvent = {\n /**\n * For this event,\n * <ul>\n * <li>The `next` function is triggered on progress updates and when the\n * task is paused/resumed with an `UploadTaskSnapshot` as the first\n * argument.</li>\n * <li>The `error` function is triggered if the upload is canceled or fails\n * for another reason.</li>\n * <li>The `complete` function is triggered if the upload completes\n * successfully.</li>\n * </ul>\n */\n STATE_CHANGED: 'state_changed'\n};\n\n/**\n * Internal enum for task state.\n */\nexport const enum InternalTaskState {\n RUNNING = 'running',\n PAUSING = 'pausing',\n PAUSED = 'paused',\n SUCCESS = 'success',\n CANCELING = 'canceling',\n CANCELED = 'canceled',\n ERROR = 'error'\n}\n\n/**\n * Represents the current state of a running upload.\n * @internal\n */\nexport type TaskState = typeof TaskState[keyof typeof TaskState];\n\n// type keys = keyof TaskState\n/**\n * Represents the current state of a running upload.\n * @internal\n */\nexport const TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n\n /** The task was paused by the user. */\n PAUSED: 'paused',\n\n /** The task completed successfully. */\n SUCCESS: 'success',\n\n /** The task was canceled. */\n CANCELED: 'canceled',\n\n /** The task failed with an error. */\n ERROR: 'error'\n} as const;\n\nexport function taskStateFromInternalTaskState(\n state: InternalTaskState\n): TaskState {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { isFunction } from './type';\nimport { StorageError } from './error';\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn<T> = (value: T) => void;\n\n/**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * An observer identical to the `Observer` defined in packages/util except the\n * error passed into the ErrorFn is specifically a `StorageError`.\n */\nexport interface StorageObserver<T> {\n /**\n * Function that is called once for each value in the event stream.\n */\n next?: NextFn<T>;\n /**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\n error?: ErrorFn;\n /**\n * A function that is called if the event stream ends normally.\n */\n complete?: CompleteFn;\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe<T> = (\n next?: NextFn<T> | StorageObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\nexport class Observer<T> implements StorageObserver<T> {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n\n constructor(\n nextOrObserver?: NextFn<T> | StorageObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n ) {\n const asFunctions =\n isFunction(nextOrObserver) || error != null || complete != null;\n if (asFunctions) {\n this.next = nextOrObserver as NextFn<T>;\n this.error = error ?? undefined;\n this.complete = complete ?? undefined;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n };\n this.next = observer.next;\n this.error = observer.error;\n this.complete = observer.complete;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(f: Function): Function {\n return (...argsToForward: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => f(...argsToForward));\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Connection,\n ConnectionType,\n ErrorCode,\n Headers\n} from '../../implementation/connection';\nimport { internalError } from '../../implementation/error';\n\n/** An override for the text-based Connection. Used in tests. */\nlet textFactoryOverride: (() => Connection<string>) | null = null;\n\n/**\n * Network layer for browsers. We use this instead of goog.net.XhrIo because\n * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.\n */\nabstract class XhrConnection<T extends ConnectionType>\n implements Connection<T>\n{\n protected xhr_: XMLHttpRequest;\n private errorCode_: ErrorCode;\n private sendPromise_: Promise<void>;\n protected sent_: boolean = false;\n\n constructor() {\n this.xhr_ = new XMLHttpRequest();\n this.initXhr();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = new Promise(resolve => {\n this.xhr_.addEventListener('abort', () => {\n this.errorCode_ = ErrorCode.ABORT;\n resolve();\n });\n this.xhr_.addEventListener('error', () => {\n this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve();\n });\n this.xhr_.addEventListener('load', () => {\n resolve();\n });\n });\n }\n\n abstract initXhr(): void;\n\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string,\n headers?: Headers\n ): Promise<void> {\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (headers !== undefined) {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n this.xhr_.setRequestHeader(key, headers[key].toString());\n }\n }\n }\n if (body !== undefined) {\n this.xhr_.send(body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n }\n\n getErrorCode(): ErrorCode {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n }\n\n getStatus(): number {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n }\n\n getResponse(): T {\n if (!this.sent_) {\n throw internalError('cannot .getResponse() before sending');\n }\n return this.xhr_.response;\n }\n\n getErrorText(): string {\n if (!this.sent_) {\n throw internalError('cannot .getErrorText() before sending');\n }\n return this.xhr_.statusText;\n }\n\n /** Aborts the request. */\n abort(): void {\n this.xhr_.abort();\n }\n\n getResponseHeader(header: string): string | null {\n return this.xhr_.getResponseHeader(header);\n }\n\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (this.xhr_.upload != null) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n }\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (this.xhr_.upload != null) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n }\n}\n\nexport class XhrTextConnection extends XhrConnection<string> {\n initXhr(): void {\n this.xhr_.responseType = 'text';\n }\n}\n\nexport function newTextConnection(): Connection<string> {\n return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\n}\n\nexport class XhrBytesConnection extends XhrConnection<ArrayBuffer> {\n private data_?: ArrayBuffer;\n\n initXhr(): void {\n this.xhr_.responseType = 'arraybuffer';\n }\n}\n\nexport function newBytesConnection(): Connection<ArrayBuffer> {\n return new XhrBytesConnection();\n}\n\nexport class XhrBlobConnection extends XhrConnection<Blob> {\n initXhr(): void {\n this.xhr_.responseType = 'blob';\n }\n}\n\nexport function newBlobConnection(): Connection<Blob> {\n return new XhrBlobConnection();\n}\n\nexport function newStreamConnection(): Connection<NodeJS.ReadableStream> {\n throw new Error('Streams are only supported on Node');\n}\n\nexport function injectTestConnection(\n factory: (() => Connection<string>) | null\n): void {\n textFactoryOverride = factory;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\nimport { FbsBlob } from './implementation/blob';\nimport {\n canceled,\n StorageErrorCode,\n StorageError,\n retryLimitExceeded\n} from './implementation/error';\nimport {\n InternalTaskState,\n TaskEvent,\n TaskState,\n taskStateFromInternalTaskState\n} from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n Observer,\n Subscribe,\n Unsubscribe,\n StorageObserver as StorageObserverInternal,\n NextFn\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport { UploadTaskSnapshot, StorageObserver } from './public-types';\nimport { async as fbsAsync } from './implementation/async';\nimport { Mappings, getMappings } from './implementation/metadata';\nimport {\n createResumableUpload,\n getResumableUploadStatus,\n RESUMABLE_UPLOAD_CHUNK_SIZE,\n ResumableUploadStatus,\n continueResumableUpload,\n getMetadata,\n multipartUpload\n} from './implementation/requests';\nimport { Reference } from './reference';\nimport { newTextConnection } from './platform/connection';\nimport { isRetryStatusCode } from './implementation/utils';\nimport { CompleteFn } from '@firebase/util';\nimport { DEFAULT_MIN_SLEEP_TIME_MILLIS } from './implementation/constants';\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n * @internal\n */\nexport class UploadTask {\n private _ref: Reference;\n /**\n * The data to be uploaded.\n */\n _blob: FbsBlob;\n /**\n * Metadata related to the upload.\n */\n _metadata: Metadata | null;\n private _mappings: Mappings;\n /**\n * Number of bytes transferred so far.\n */\n _transferred: number = 0;\n private _needToFetchStatus: boolean = false;\n private _needToFetchMetadata: boolean = false;\n private _observers: Array<StorageObserverInternal<UploadTaskSnapshot>> = [];\n private _resumable: boolean;\n /**\n * Upload state.\n */\n _state: InternalTaskState;\n private _error?: StorageError = undefined;\n private _uploadUrl?: string = undefined;\n private _request?: Request<unknown> = undefined;\n private _chunkMultiplier: number = 1;\n private _errorHandler: (p1: StorageError) => void;\n private _metadataErrorHandler: (p1: StorageError) => void;\n private _resolve?: (p1: UploadTaskSnapshot) => void = undefined;\n private _reject?: (p1: StorageError) => void = undefined;\n private pendingTimeout?: ReturnType<typeof setTimeout>;\n private _promise: Promise<UploadTaskSnapshot>;\n\n private sleepTime: number;\n\n private maxSleepTime: number;\n\n isExponentialBackoffExpired(): boolean {\n return this.sleepTime > this.maxSleepTime;\n }\n\n /**\n * @param ref - The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob - The blob to upload.\n */\n constructor(ref: Reference, blob: FbsBlob, metadata: Metadata | null = null) {\n this._ref = ref;\n this._blob = blob;\n this._metadata = metadata;\n this._mappings = getMappings();\n this._resumable = this._shouldDoResumable(this._blob);\n this._state = InternalTaskState.RUNNING;\n this._errorHandler = error => {\n this._request = undefined;\n this._chunkMultiplier = 1;\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\n this._needToFetchStatus = true;\n this.completeTransitions_();\n } else {\n const backoffExpired = this.isExponentialBackoffExpired();\n if (isRetryStatusCode(error.status, [])) {\n if (backoffExpired) {\n error = retryLimitExceeded();\n } else {\n this.sleepTime = Math.max(\n this.sleepTime * 2,\n DEFAULT_MIN_SLEEP_TIME_MILLIS\n );\n this._needToFetchStatus = true;\n this.completeTransitions_();\n return;\n }\n }\n this._error = error;\n this._transition(InternalTaskState.ERROR);\n }\n };\n this._metadataErrorHandler = error => {\n this._request = undefined;\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\n this.completeTransitions_();\n } else {\n this._error = error;\n this._transition(InternalTaskState.ERROR);\n }\n };\n this.sleepTime = 0;\n this.maxSleepTime = this._ref.storage.maxUploadRetryTime;\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n this._start();\n });\n\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this._promise.then(null, () => {});\n }\n\n private _makeProgressCallback(): (p1: number, p2: number) => void {\n const sizeBefore = this._transferred;\n return loaded => this._updateProgress(sizeBefore + loaded);\n }\n\n private _shouldDoResumable(blob: FbsBlob): boolean {\n return blob.size() > 256 * 1024;\n }\n\n private _start(): void {\n if (this._state !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this._request !== undefined) {\n return;\n }\n if (this._resumable) {\n if (this._uploadUrl === undefined) {\n this._createResumable();\n } else {\n if (this._needToFetchStatus) {\n this._fetchStatus();\n } else {\n if (this._needToFetchMetadata) {\n // Happens if we miss the metadata on upload completion.\n this._fetchMetadata();\n } else {\n this.pendingTimeout = setTimeout(() => {\n this.pendingTimeout = undefined;\n this._continueUpload();\n }, this.sleepTime);\n }\n }\n }\n } else {\n this._oneShotUpload();\n }\n }\n\n private _resolveToken(\n callback: (authToken: string | null, appCheckToken: string | null) => void\n ): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all([\n this._ref.storage._getAuthToken(),\n this._ref.storage._getAppCheckToken()\n ]).then(([authToken, appCheckToken]) => {\n switch (this._state) {\n case InternalTaskState.RUNNING:\n callback(authToken, appCheckToken);\n break;\n case InternalTaskState.CANCELING:\n this._transition(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n this._transition(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n }\n\n // TODO(andysoto): assert false\n\n private _createResumable(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = createResumableUpload(\n this._ref.storage,\n this._ref._location,\n this._mappings,\n this._blob,\n this._metadata\n );\n const createRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = createRequest;\n createRequest.getPromise().then((url: string) => {\n this._request = undefined;\n this._uploadUrl = url;\n this._needToFetchStatus = false;\n this.completeTransitions_();\n }, this._errorHandler);\n });\n }\n\n private _fetchStatus(): void {\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this._uploadUrl as string;\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = getResumableUploadStatus(\n this._ref.storage,\n this._ref._location,\n url,\n this._blob\n );\n const statusRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = statusRequest;\n statusRequest.getPromise().then(status => {\n status = status as ResumableUploadStatus;\n this._request = undefined;\n this._updateProgress(status.current);\n this._needToFetchStatus = false;\n if (status.finalized) {\n this._needToFetchMetadata = true;\n }\n this.completeTransitions_();\n }, this._errorHandler);\n });\n }\n\n private _continueUpload(): void {\n const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n const status = new ResumableUploadStatus(\n this._transferred,\n this._blob.size()\n );\n\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this._uploadUrl as string;\n this._resolveToken((authToken, appCheckToken) => {\n let requestInfo;\n try {\n requestInfo = continueResumableUpload(\n this._ref._location,\n this._ref.storage,\n url,\n this._blob,\n chunkSize,\n this._mappings,\n status,\n this._makeProgressCallback()\n );\n } catch (e) {\n this._error = e as StorageError;\n this._transition(InternalTaskState.ERROR);\n return;\n }\n const uploadRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken,\n /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.\n );\n this._request = uploadRequest;\n uploadRequest.getPromise().then((newStatus: ResumableUploadStatus) => {\n this._increaseMultiplier();\n this._request = undefined;\n this._updateProgress(newStatus.current);\n if (newStatus.finalized) {\n this._metadata = newStatus.metadata;\n this._transition(InternalTaskState.SUCCESS);\n } else {\n this.completeTransitions_();\n }\n }, this._errorHandler);\n });\n }\n\n private _increaseMultiplier(): void {\n const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n\n // Max chunk size is 32M.\n if (currentSize * 2 < 32 * 1024 * 1024) {\n this._chunkMultiplier *= 2;\n }\n }\n\n private _fetchMetadata(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = getMetadata(\n this._ref.storage,\n this._ref._location,\n this._mappings\n );\n const metadataRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = metadataRequest;\n metadataRequest.getPromise().then(metadata => {\n this._request = undefined;\n this._metadata = metadata;\n this._transition(InternalTaskState.SUCCESS);\n }, this._metadataErrorHandler);\n });\n }\n\n private _oneShotUpload(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = multipartUpload(\n this._ref.storage,\n this._ref._location,\n this._mappings,\n this._blob,\n this._metadata\n );\n const multipartRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = multipartRequest;\n multipartRequest.getPromise().then(metadata => {\n this._request = undefined;\n this._metadata = metadata;\n this._updateProgress(this._blob.size());\n this._transition(InternalTaskState.SUCCESS);\n }, this._errorHandler);\n });\n }\n\n private _updateProgress(transferred: number): void {\n const old = this._transferred;\n this._transferred = transferred;\n\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this._transferred !== old) {\n this._notifyObservers();\n }\n }\n\n private _transition(state: InternalTaskState): void {\n if (this._state === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this._state = state;\n if (this._request !== undefined) {\n this._request.cancel();\n } else if (this.pendingTimeout) {\n clearTimeout(this.pendingTimeout);\n this.pendingTimeout = undefined;\n this.completeTransitions_();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n const wasPaused = this._state === InternalTaskState.PAUSED;\n this._state = state;\n if (wasPaused) {\n this._notifyObservers();\n this._start();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this._state = state;\n this._notifyObservers();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this._error = canceled();\n this._state = state;\n this._notifyObservers();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this._state = state;\n this._notifyObservers();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this._state = state;\n this._notifyObservers();\n break;\n default: // Ignore\n }\n }\n\n private completeTransitions_(): void {\n switch (this._state) {\n case InternalTaskState.PAUSING:\n this._transition(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this._transition(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this._start();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n }\n\n /**\n * A snapshot of the current task state.\n */\n get snapshot(): UploadTaskSnapshot {\n const externalState = taskStateFromInternalTaskState(this._state);\n return {\n bytesTransferred: this._transferred,\n totalBytes: this._blob.size(),\n state: externalState,\n metadata: this._metadata!,\n task: this,\n ref: this._ref\n };\n }\n\n /**\n * Adds a callback for an event.\n * @param type - The type of event to listen for.\n * @param nextOrObserver -\n * The `next` function, which gets called for each item in\n * the event stream, or an observer object with some or all of these three\n * properties (`next`, `error`, `complete`).\n * @param error - A function that gets called with a `StorageError`\n * if the event stream ends due to an error.\n * @param completed - A function that gets called if the\n * event stream ends normally.\n * @returns\n * If only the event argument is passed, returns a function you can use to\n * add callbacks (see the examples above). If more than just the event\n * argument is passed, returns a function you can call to unregister the\n * callbacks.\n */\n on(\n type: TaskEvent,\n nextOrObserver?:\n | StorageObserver<UploadTaskSnapshot>\n | null\n | ((snapshot: UploadTaskSnapshot) => unknown),\n error?: ((a: StorageError) => unknown) | null,\n completed?: CompleteFn | null\n ): Unsubscribe | Subscribe<UploadTaskSnapshot> {\n // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.\n const observer = new Observer(\n (nextOrObserver as\n | StorageObserverInternal<UploadTaskSnapshot>\n | NextFn<UploadTaskSnapshot>) || undefined,\n error || undefined,\n completed || undefined\n );\n this._addObserver(observer);\n return () => {\n this._removeObserver(observer);\n };\n }\n\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.\n * @param onRejected - The rejection callback.\n */\n then<U>(\n onFulfilled?: ((value: UploadTaskSnapshot) => U | Promise<U>) | null,\n onRejected?: ((error: StorageError) => U | Promise<U>) | null\n ): Promise<U> {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this._promise.then<U>(\n onFulfilled as (value: UploadTaskSnapshot) => U | Promise<U>,\n onRejected as ((error: unknown) => Promise<never>) | null\n );\n }\n\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n catch<T>(onRejected: (p1: StorageError) => T | Promise<T>): Promise<T> {\n return this.then(null, onRejected);\n }\n\n /**\n * Adds the given observer.\n */\n private _addObserver(observer: Observer<UploadTaskSnapshot>): void {\n this._observers.push(observer);\n this._notifyObserver(observer);\n }\n\n /**\n * Removes the given observer.\n */\n private _removeObserver(observer: Observer<UploadTaskSnapshot>): void {\n const i = this._observers.indexOf(observer);\n if (i !== -1) {\n this._observers.splice(i, 1);\n }\n }\n\n private _notifyObservers(): void {\n this._finishPromise();\n const observers = this._observers.slice();\n observers.forEach(observer => {\n this._notifyObserver(observer);\n });\n }\n\n private _finishPromise(): void {\n if (this._resolve !== undefined) {\n let triggered = true;\n switch (taskStateFromInternalTaskState(this._state)) {\n case TaskState.SUCCESS:\n fbsAsync(this._resolve.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n const toCall = this._reject as (p1: StorageError) => void;\n fbsAsync(toCall.bind(null, this._error as StorageError))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this._resolve = undefined;\n this._reject = undefined;\n }\n }\n }\n\n private _notifyObserver(observer: Observer<UploadTaskSnapshot>): void {\n const externalState = taskStateFromInternalTaskState(this._state);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error) {\n fbsAsync(\n observer.error.bind(observer, this._error as StorageError)\n )();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error) {\n fbsAsync(\n observer.error.bind(observer, this._error as StorageError)\n )();\n }\n }\n }\n\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n resume(): boolean {\n const valid =\n this._state === InternalTaskState.PAUSED ||\n this._state === InternalTaskState.PAUSING;\n if (valid) {\n this._transition(InternalTaskState.RUNNING);\n }\n return valid;\n }\n\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n pause(): boolean {\n const valid = this._state === InternalTaskState.RUNNING;\n if (valid) {\n this._transition(InternalTaskState.PAUSING);\n }\n return valid;\n }\n\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n cancel(): boolean {\n const valid =\n this._state === InternalTaskState.RUNNING ||\n this._state === InternalTaskState.PAUSING;\n if (valid) {\n this._transition(InternalTaskState.CANCELING);\n }\n return valid;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines the Firebase StorageReference class.\n */\n\nimport { PassThrough, Transform, TransformOptions } from 'stream';\n\nimport { FbsBlob } from './implementation/blob';\nimport { Location } from './implementation/location';\nimport { getMappings } from './implementation/metadata';\nimport { child, lastComponent, parent } from './implementation/path';\nimport {\n deleteObject as requestsDeleteObject,\n getBytes,\n getDownloadUrl as requestsGetDownloadUrl,\n getMetadata as requestsGetMetadata,\n list as requestsList,\n multipartUpload,\n updateMetadata as requestsUpdateMetadata\n} from './implementation/requests';\nimport { ListOptions, UploadResult } from './public-types';\nimport { dataFromString, StringFormat } from './implementation/string';\nimport { Metadata } from './metadata';\nimport { FirebaseStorageImpl } from './service';\nimport { ListResult } from './list';\nimport { UploadTask } from './task';\nimport { invalidRootOperation, noDownloadURL } from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport {\n newBlobConnection,\n newBytesConnection,\n newStreamConnection,\n newTextConnection\n} from './platform/connection';\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @internal\n * @param _location - An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs://<bucket>/<object-path>\n * http[s]://firebasestorage.googleapis.com/\n * <api-version>/b/<bucket>/o/<object-path>\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nexport class Reference {\n _location: Location;\n\n constructor(\n private _service: FirebaseStorageImpl,\n location: string | Location\n ) {\n if (location instanceof Location) {\n this._location = location;\n } else {\n this._location = Location.makeFromUrl(location, _service.host);\n }\n }\n\n /**\n * Returns the URL for the bucket and path this object references,\n * in the form gs://<bucket>/<object-path>\n * @override\n */\n toString(): string {\n return 'gs://' + this._location.bucket + '/' + this._location.path;\n }\n\n protected _newRef(\n service: FirebaseStorageImpl,\n location: Location\n ): Reference {\n return new Reference(service, location);\n }\n\n /**\n * A reference to the root of this object's bucket.\n */\n get root(): Reference {\n const location = new Location(this._location.bucket, '');\n return this._newRef(this._service, location);\n }\n\n /**\n * The name of the bucket containing this reference's object.\n */\n get bucket(): string {\n return this._location.bucket;\n }\n\n /**\n * The full path of this object.\n */\n get fullPath(): string {\n return this._location.path;\n }\n\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if fullPath is 'full/path/image.png', name is 'image.png'.\n */\n get name(): string {\n return lastComponent(this._location.path);\n }\n\n /**\n * The `StorageService` instance this `StorageReference` is associated with.\n */\n get storage(): FirebaseStorageImpl {\n return this._service;\n }\n\n /**\n * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if\n * this reference is the root.\n */\n get parent(): Reference | null {\n const newPath = parent(this._location.path);\n if (newPath === null) {\n return null;\n }\n const location = new Location(this._location.bucket, newPath);\n return new Reference(this._service, location);\n }\n\n /**\n * Utility function to throw an error in methods that do not accept a root reference.\n */\n _throwIfRoot(name: string): void {\n if (this._location.path === '') {\n throw invalidRootOperation(name);\n }\n }\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded bytes.\n */\nexport function getBytesInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): Promise<ArrayBuffer> {\n ref._throwIfRoot('getBytes');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newBytesConnection)\n .then(bytes =>\n maxDownloadSizeBytes !== undefined\n ? // GCS may not honor the Range header for small files\n (bytes as ArrayBuffer).slice(0, maxDownloadSizeBytes)\n : (bytes as ArrayBuffer)\n );\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded blob.\n */\nexport function getBlobInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): Promise<Blob> {\n ref._throwIfRoot('getBlob');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newBlobConnection)\n .then(blob =>\n maxDownloadSizeBytes !== undefined\n ? // GCS may not honor the Range header for small files\n (blob as Blob).slice(0, maxDownloadSizeBytes)\n : (blob as Blob)\n );\n}\n\n/** Stream the bytes at the object's location. */\nexport function getStreamInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): NodeJS.ReadableStream {\n ref._throwIfRoot('getStream');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n\n /** A transformer that passes through the first n bytes. */\n const newMaxSizeTransform: (n: number) => TransformOptions = n => {\n let missingBytes = n;\n return {\n transform(chunk, encoding, callback) {\n // GCS may not honor the Range header for small files\n if (chunk.length < missingBytes) {\n this.push(chunk);\n missingBytes -= chunk.length;\n } else {\n this.push(chunk.slice(0, missingBytes));\n this.emit('end');\n }\n callback();\n }\n } as TransformOptions;\n };\n\n const result =\n maxDownloadSizeBytes !== undefined\n ? new Transform(newMaxSizeTransform(maxDownloadSizeBytes))\n : new PassThrough();\n\n ref.storage\n .makeRequestWithTokens(requestInfo, newStreamConnection)\n .then(stream => (stream as NodeJS.ReadableStream).pipe(result))\n .catch(e => result.destroy(e));\n return result;\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n *\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n ref: Reference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: Metadata\n): Promise<UploadResult> {\n ref._throwIfRoot('uploadBytes');\n const requestInfo = multipartUpload(\n ref.storage,\n ref._location,\n getMappings(),\n new FbsBlob(data, true),\n metadata\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newTextConnection)\n .then(finalMetadata => {\n return {\n metadata: finalMetadata,\n ref\n };\n });\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n ref: Reference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: Metadata\n): UploadTask {\n ref._throwIfRoot('uploadBytesResumable');\n return new UploadTask(ref, new FbsBlob(data), metadata);\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - StorageReference where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the newly uploaded string.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n ref: Reference,\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: Metadata\n): Promise<UploadResult> {\n ref._throwIfRoot('uploadString');\n const data = dataFromString(format, value);\n const metadataClone = { ...metadata } as Metadata;\n if (metadataClone['contentType'] == null && data.contentType != null) {\n metadataClone['contentType'] = data.contentType!;\n }\n return uploadBytes(ref, data.data, metadataClone);\n}\n\n/**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: listAll may potentially consume too many resources if there are\n * too many results.\n * @public\n * @param ref - StorageReference to get list from.\n *\n * @returns A Promise that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\nexport function listAll(ref: Reference): Promise<ListResult> {\n const accumulator: ListResult = {\n prefixes: [],\n items: []\n };\n return listAllHelper(ref, accumulator).then(() => accumulator);\n}\n\n/**\n * Separated from listAll because async functions can't use \"arguments\".\n * @param ref\n * @param accumulator\n * @param pageToken\n */\nasync function listAllHelper(\n ref: Reference,\n accumulator: ListResult,\n pageToken?: string\n): Promise<void> {\n const opt: ListOptions = {\n // maxResults is 1000 by default.\n pageToken\n };\n const nextPage = await list(ref, opt);\n accumulator.prefixes.push(...nextPage.prefixes);\n accumulator.items.push(...nextPage.items);\n if (nextPage.nextPageToken != null) {\n await listAllHelper(ref, accumulator, nextPage.nextPageToken);\n }\n}\n\n/**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure.\n * Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n * @public\n *\n * @param ref - StorageReference to get list from.\n * @param options - See ListOptions for details.\n * @returns A Promise that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\nexport function list(\n ref: Reference,\n options?: ListOptions | null\n): Promise<ListResult> {\n if (options != null) {\n if (typeof options.maxResults === 'number') {\n validateNumber(\n 'options.maxResults',\n /* minValue= */ 1,\n /* maxValue= */ 1000,\n options.maxResults\n );\n }\n }\n const op = options || {};\n const requestInfo = requestsList(\n ref.storage,\n ref._location,\n /*delimiter= */ '/',\n op.pageToken,\n op.maxResults\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * A `Promise` that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n * @public\n * @param ref - StorageReference to get metadata from.\n */\nexport function getMetadata(ref: Reference): Promise<Metadata> {\n ref._throwIfRoot('getMetadata');\n const requestInfo = requestsGetMetadata(\n ref.storage,\n ref._location,\n getMappings()\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - StorageReference to update metadata for.\n * @param metadata - The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @returns A `Promise` that resolves\n * with the new metadata for this object.\n * See `firebaseStorage.Reference.prototype.getMetadata`\n */\nexport function updateMetadata(\n ref: Reference,\n metadata: Partial<Metadata>\n): Promise<Metadata> {\n ref._throwIfRoot('updateMetadata');\n const requestInfo = requestsUpdateMetadata(\n ref.storage,\n ref._location,\n metadata,\n getMappings()\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns the download URL for the given Reference.\n * @public\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\nexport function getDownloadURL(ref: Reference): Promise<string> {\n ref._throwIfRoot('getDownloadURL');\n const requestInfo = requestsGetDownloadUrl(\n ref.storage,\n ref._location,\n getMappings()\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newTextConnection)\n .then(url => {\n if (url === null) {\n throw noDownloadURL();\n }\n return url;\n });\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - StorageReference for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: Reference): Promise<void> {\n ref._throwIfRoot('deleteObject');\n const requestInfo = requestsDeleteObject(ref.storage, ref._location);\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns reference for object obtained by appending `childPath` to `ref`.\n *\n * @param ref - StorageReference to get child of.\n * @param childPath - Child path from provided ref.\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n *\n */\nexport function _getChild(ref: Reference, childPath: string): Reference {\n const newPath = child(ref._location.path, childPath);\n const location = new Location(ref._location.bucket, newPath);\n return new Reference(ref.storage, location);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Location } from './implementation/location';\nimport { FailRequest } from './implementation/failrequest';\nimport { Request, makeRequest } from './implementation/request';\nimport { RequestInfo } from './implementation/requestinfo';\nimport { Reference, _getChild } from './reference';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport {\n CONFIG_STORAGE_BUCKET_KEY,\n DEFAULT_HOST,\n DEFAULT_MAX_OPERATION_RETRY_TIME,\n DEFAULT_MAX_UPLOAD_RETRY_TIME\n} from './implementation/constants';\nimport {\n invalidArgument,\n appDeleted,\n noDefaultBucket\n} from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport { FirebaseStorage } from './public-types';\nimport { createMockUserToken, EmulatorMockTokenOptions } from '@firebase/util';\nimport { Connection, ConnectionType } from './implementation/connection';\n\nexport function isUrl(path?: string): boolean {\n return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given url.\n */\nfunction refFromURL(service: FirebaseStorageImpl, url: string): Reference {\n return new Reference(service, url);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\nfunction refFromPath(\n ref: FirebaseStorageImpl | Reference,\n path?: string\n): Reference {\n if (ref instanceof FirebaseStorageImpl) {\n const service = ref;\n if (service._bucket == null) {\n throw noDefaultBucket();\n }\n const reference = new Reference(service, service._bucket!);\n if (path != null) {\n return refFromPath(reference, path);\n } else {\n return reference;\n }\n } else {\n // ref is a Reference\n if (path !== undefined) {\n return _getChild(ref, path);\n } else {\n return ref;\n }\n }\n}\n\n/**\n * Returns a storage Reference for the given url.\n * @param storage - `Storage` instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorageImpl, url?: string): Reference;\n/**\n * Returns a storage Reference for the given path in the\n * default bucket.\n * @param storageOrRef - `Storage` service or storage `Reference`.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if Storage\n * instance provided) or returns same reference (if Reference provided).\n * @public\n */\nexport function ref(\n storageOrRef: FirebaseStorageImpl | Reference,\n path?: string\n): Reference;\nexport function ref(\n serviceOrRef: FirebaseStorageImpl | Reference,\n pathOrUrl?: string\n): Reference | null {\n if (pathOrUrl && isUrl(pathOrUrl)) {\n if (serviceOrRef instanceof FirebaseStorageImpl) {\n return refFromURL(serviceOrRef, pathOrUrl);\n } else {\n throw invalidArgument(\n 'To use ref(service, url), the first argument must be a Storage instance.'\n );\n }\n } else {\n return refFromPath(serviceOrRef, pathOrUrl);\n }\n}\n\nfunction extractBucket(\n host: string,\n config?: FirebaseOptions\n): Location | null {\n const bucketString = config?.[CONFIG_STORAGE_BUCKET_KEY];\n if (bucketString == null) {\n return null;\n }\n return Location.makeFromBucketSpec(bucketString, host);\n}\n\nexport function connectStorageEmulator(\n storage: FirebaseStorageImpl,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n storage.host = `${host}:${port}`;\n storage._protocol = 'http';\n const { mockUserToken } = options;\n if (mockUserToken) {\n storage._overrideAuthToken =\n typeof mockUserToken === 'string'\n ? mockUserToken\n : createMockUserToken(mockUserToken, storage.app.options.projectId);\n }\n}\n\n/**\n * A service that provides Firebase Storage Reference instances.\n * @param opt_url - gs:// url to a custom Storage Bucket\n *\n * @internal\n */\nexport class FirebaseStorageImpl implements FirebaseStorage {\n _bucket: Location | null = null;\n /**\n * This string can be in the formats:\n * - host\n * - host:port\n */\n private _host: string = DEFAULT_HOST;\n _protocol: string = 'https';\n protected readonly _appId: string | null = null;\n private readonly _requests: Set<Request<unknown>>;\n private _deleted: boolean = false;\n private _maxOperationRetryTime: number;\n private _maxUploadRetryTime: number;\n _overrideAuthToken?: string;\n\n constructor(\n /**\n * FirebaseApp associated with this StorageService instance.\n */\n readonly app: FirebaseApp,\n readonly _authProvider: Provider<FirebaseAuthInternalName>,\n /**\n * @internal\n */\n readonly _appCheckProvider: Provider<AppCheckInternalComponentName>,\n /**\n * @internal\n */\n readonly _url?: string,\n readonly _firebaseVersion?: string\n ) {\n this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;\n this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;\n this._requests = new Set();\n if (_url != null) {\n this._bucket = Location.makeFromBucketSpec(_url, this._host);\n } else {\n this._bucket = extractBucket(this._host, this.app.options);\n }\n }\n\n /**\n * The host string for this service, in the form of `host` or\n * `host:port`.\n */\n get host(): string {\n return this._host;\n }\n\n set host(host: string) {\n this._host = host;\n if (this._url != null) {\n this._bucket = Location.makeFromBucketSpec(this._url, host);\n } else {\n this._bucket = extractBucket(host, this.app.options);\n }\n }\n\n /**\n * The maximum time to retry uploads in milliseconds.\n */\n get maxUploadRetryTime(): number {\n return this._maxUploadRetryTime;\n }\n\n set maxUploadRetryTime(time: number) {\n validateNumber(\n 'time',\n /* minValue=*/ 0,\n /* maxValue= */ Number.POSITIVE_INFINITY,\n time\n );\n this._maxUploadRetryTime = time;\n }\n\n /**\n * The maximum time to retry operations other than uploads or downloads in\n * milliseconds.\n */\n get maxOperationRetryTime(): number {\n return this._maxOperationRetryTime;\n }\n\n set maxOperationRetryTime(time: number) {\n validateNumber(\n 'time',\n /* minValue=*/ 0,\n /* maxValue= */ Number.POSITIVE_INFINITY,\n time\n );\n this._maxOperationRetryTime = time;\n }\n\n async _getAuthToken(): Promise<string | null> {\n if (this._overrideAuthToken) {\n return this._overrideAuthToken;\n }\n const auth = this._authProvider.getImmediate({ optional: true });\n if (auth) {\n const tokenData = await auth.getToken();\n if (tokenData !== null) {\n return tokenData.accessToken;\n }\n }\n return null;\n }\n\n async _getAppCheckToken(): Promise<string | null> {\n const appCheck = this._appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n const result = await appCheck.getToken();\n // TODO: What do we want to do if there is an error getting the token?\n // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be\n // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n return result.token;\n }\n return null;\n }\n\n /**\n * Stop running requests and prevent more from being created.\n */\n _delete(): Promise<void> {\n if (!this._deleted) {\n this._deleted = true;\n this._requests.forEach(request => request.cancel());\n this._requests.clear();\n }\n return Promise.resolve();\n }\n\n /**\n * Returns a new firebaseStorage.Reference object referencing this StorageService\n * at the given Location.\n */\n _makeStorageReference(loc: Location): Reference {\n return new Reference(this, loc);\n }\n\n /**\n * @param requestInfo - HTTP RequestInfo object\n * @param authToken - Firebase auth token\n */\n _makeRequest<I extends ConnectionType, O>(\n requestInfo: RequestInfo<I, O>,\n requestFactory: () => Connection<I>,\n authToken: string | null,\n appCheckToken: string | null,\n retry = true\n ): Request<O> {\n if (!this._deleted) {\n const request = makeRequest(\n requestInfo,\n this._appId,\n authToken,\n appCheckToken,\n requestFactory,\n this._firebaseVersion,\n retry\n );\n this._requests.add(request);\n // Request removes itself from set when complete.\n request.getPromise().then(\n () => this._requests.delete(request),\n () => this._requests.delete(request)\n );\n return request;\n } else {\n return new FailRequest(appDeleted());\n }\n }\n\n async makeRequestWithTokens<I extends ConnectionType, O>(\n requestInfo: RequestInfo<I, O>,\n requestFactory: () => Connection<I>\n ): Promise<O> {\n const [authToken, appCheckToken] = await Promise.all([\n this._getAuthToken(),\n this._getAppCheckToken()\n ]);\n\n return this._makeRequest(\n requestInfo,\n requestFactory,\n authToken,\n appCheckToken\n ).getPromise();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\n\nimport {\n ref as refInternal,\n FirebaseStorageImpl,\n connectStorageEmulator as connectEmulatorInternal\n} from './service';\nimport { Provider } from '@firebase/component';\n\nimport {\n StorageReference,\n FirebaseStorage,\n UploadResult,\n ListOptions,\n ListResult,\n UploadTask,\n SettableMetadata,\n UploadMetadata,\n FullMetadata\n} from './public-types';\nimport { Metadata as MetadataInternal } from './metadata';\nimport {\n uploadBytes as uploadBytesInternal,\n uploadBytesResumable as uploadBytesResumableInternal,\n uploadString as uploadStringInternal,\n getMetadata as getMetadataInternal,\n updateMetadata as updateMetadataInternal,\n list as listInternal,\n listAll as listAllInternal,\n getDownloadURL as getDownloadURLInternal,\n deleteObject as deleteObjectInternal,\n Reference,\n _getChild as _getChildInternal,\n getBytesInternal\n} from './reference';\nimport { STORAGE_TYPE } from './constants';\nimport {\n EmulatorMockTokenOptions,\n getModularInstance,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\nimport { StringFormat } from './implementation/string';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\n/**\n * Public types.\n */\nexport * from './public-types';\n\nexport { Location as _Location } from './implementation/location';\nexport { UploadTask as _UploadTask } from './task';\nexport type { Reference as _Reference } from './reference';\nexport type { FirebaseStorageImpl as _FirebaseStorageImpl } from './service';\nexport { FbsBlob as _FbsBlob } from './implementation/blob';\nexport { dataFromString as _dataFromString } from './implementation/string';\nexport {\n invalidRootOperation as _invalidRootOperation,\n invalidArgument as _invalidArgument\n} from './implementation/error';\nexport {\n TaskEvent as _TaskEvent,\n TaskState as _TaskState\n} from './implementation/taskenums';\nexport { StringFormat };\n\n/**\n * Downloads the data at the object's location. Returns an error if the object\n * is not found.\n *\n * To use this functionality, you have to whitelist your app's origin in your\n * Cloud Storage bucket. See also\n * https://cloud.google.com/storage/docs/configuring-cors\n *\n * @public\n * @param ref - StorageReference where data should be downloaded.\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\n * retrieve.\n * @returns A Promise containing the object's bytes\n */\nexport function getBytes(\n ref: StorageReference,\n maxDownloadSizeBytes?: number\n): Promise<ArrayBuffer> {\n ref = getModularInstance(ref);\n return getBytesInternal(ref as Reference, maxDownloadSizeBytes);\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n ref: StorageReference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: UploadMetadata\n): Promise<UploadResult> {\n ref = getModularInstance(ref);\n return uploadBytesInternal(\n ref as Reference,\n data,\n metadata as MetadataInternal\n );\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the string to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n ref: StorageReference,\n value: string,\n format?: StringFormat,\n metadata?: UploadMetadata\n): Promise<UploadResult> {\n ref = getModularInstance(ref);\n return uploadStringInternal(\n ref as Reference,\n value,\n format,\n metadata as MetadataInternal\n );\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n ref: StorageReference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: UploadMetadata\n): UploadTask {\n ref = getModularInstance(ref);\n return uploadBytesResumableInternal(\n ref as Reference,\n data,\n metadata as MetadataInternal\n ) as UploadTask;\n}\n\n/**\n * A `Promise` that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n * @public\n * @param ref - {@link StorageReference} to get metadata from.\n */\nexport function getMetadata(ref: StorageReference): Promise<FullMetadata> {\n ref = getModularInstance(ref);\n return getMetadataInternal(ref as Reference) as Promise<FullMetadata>;\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - {@link StorageReference} to update metadata for.\n * @param metadata - The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @returns A `Promise` that resolves with the new metadata for this object.\n */\nexport function updateMetadata(\n ref: StorageReference,\n metadata: SettableMetadata\n): Promise<FullMetadata> {\n ref = getModularInstance(ref);\n return updateMetadataInternal(\n ref as Reference,\n metadata as Partial<MetadataInternal>\n ) as Promise<FullMetadata>;\n}\n\n/**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure.\n * Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n * @public\n *\n * @param ref - {@link StorageReference} to get list from.\n * @param options - See {@link ListOptions} for details.\n * @returns A `Promise` that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\nexport function list(\n ref: StorageReference,\n options?: ListOptions\n): Promise<ListResult> {\n ref = getModularInstance(ref);\n return listInternal(ref as Reference, options);\n}\n\n/**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: `listAll` may potentially consume too many resources if there are\n * too many results.\n * @public\n * @param ref - {@link StorageReference} to get list from.\n *\n * @returns A `Promise` that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\nexport function listAll(ref: StorageReference): Promise<ListResult> {\n ref = getModularInstance(ref);\n return listAllInternal(ref as Reference);\n}\n\n/**\n * Returns the download URL for the given {@link StorageReference}.\n * @public\n * @param ref - {@link StorageReference} to get the download URL for.\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\nexport function getDownloadURL(ref: StorageReference): Promise<string> {\n ref = getModularInstance(ref);\n return getDownloadURLInternal(ref as Reference);\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - {@link StorageReference} for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: StorageReference): Promise<void> {\n ref = getModularInstance(ref);\n return deleteObjectInternal(ref as Reference);\n}\n\n/**\n * Returns a {@link StorageReference} for the given url.\n * @param storage - {@link FirebaseStorage} instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorage, url?: string): StorageReference;\n/**\n * Returns a {@link StorageReference} for the given path in the\n * default bucket.\n * @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage}\n * instance provided) or returns same reference (if {@link StorageReference} provided).\n * @public\n */\nexport function ref(\n storageOrRef: FirebaseStorage | StorageReference,\n path?: string\n): StorageReference;\nexport function ref(\n serviceOrRef: FirebaseStorage | StorageReference,\n pathOrUrl?: string\n): StorageReference | null {\n serviceOrRef = getModularInstance(serviceOrRef);\n return refInternal(\n serviceOrRef as FirebaseStorageImpl | Reference,\n pathOrUrl\n );\n}\n\n/**\n * @internal\n */\nexport function _getChild(ref: StorageReference, childPath: string): Reference {\n return _getChildInternal(ref as Reference, childPath);\n}\n\n/**\n * Gets a {@link FirebaseStorage} instance for the given Firebase app.\n * @public\n * @param app - Firebase app to get {@link FirebaseStorage} instance for.\n * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.\n * If not passed, uses the app's default Storage Bucket.\n * @returns A {@link FirebaseStorage} instance.\n */\nexport function getStorage(\n app: FirebaseApp = getApp(),\n bucketUrl?: string\n): FirebaseStorage {\n app = getModularInstance(app);\n const storageProvider: Provider<'storage'> = _getProvider(app, STORAGE_TYPE);\n const storageInstance = storageProvider.getImmediate({\n identifier: bucketUrl\n });\n const emulator = getDefaultEmulatorHostnameAndPort('storage');\n if (emulator) {\n connectStorageEmulator(storageInstance, ...emulator);\n }\n return storageInstance;\n}\n\n/**\n * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.\n *\n * @param storage - The {@link FirebaseStorage} instance\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 5001)\n * @param options - Emulator options. `options.mockUserToken` is the mock auth\n * token to use for unit testing Security Rules.\n * @public\n */\nexport function connectStorageEmulator(\n storage: FirebaseStorage,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n connectEmulatorInternal(storage as FirebaseStorageImpl, host, port, options);\n}\n","/**\n * Cloud Storage for Firebase\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\n\nimport { FirebaseStorageImpl } from '../src/service';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\nimport { FirebaseStorage } from './public-types';\nimport { STORAGE_TYPE } from './constants';\n\nexport * from './api';\nexport * from './api.browser';\n\nfunction factory(\n container: ComponentContainer,\n { instanceIdentifier: url }: InstanceFactoryOptions\n): FirebaseStorage {\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n\n return new FirebaseStorageImpl(\n app,\n authProvider,\n appCheckProvider,\n url,\n SDK_VERSION\n );\n}\n\nfunction registerStorage(): void {\n _registerComponent(\n new Component(\n STORAGE_TYPE,\n factory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n //RUNTIME_ENV will be replaced during the compilation to \"node\" for nodejs and an empty string for browser\n registerVersion(name, version, '__RUNTIME_ENV__');\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterStorage();\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Storage.\n */\nexport const STORAGE_TYPE = 'storage';\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UploadTaskSnapshot } from '@firebase/storage';\nimport { ReferenceCompat } from './reference';\nimport { UploadTaskCompat } from './task';\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class UploadTaskSnapshotCompat\n implements types.UploadTaskSnapshot, Compat<UploadTaskSnapshot>\n{\n constructor(\n readonly _delegate: UploadTaskSnapshot,\n readonly task: UploadTaskCompat,\n readonly ref: ReferenceCompat\n ) {}\n\n get bytesTransferred(): number {\n return this._delegate.bytesTransferred;\n }\n get metadata(): types.FullMetadata {\n return this._delegate.metadata as types.FullMetadata;\n }\n get state(): string {\n return this._delegate.state;\n }\n get totalBytes(): number {\n return this._delegate.totalBytes;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n UploadTask,\n StorageError,\n UploadTaskSnapshot,\n TaskEvent,\n StorageObserver\n} from '@firebase/storage';\nimport { UploadTaskSnapshotCompat } from './tasksnapshot';\nimport { ReferenceCompat } from './reference';\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class UploadTaskCompat implements types.UploadTask, Compat<UploadTask> {\n constructor(\n readonly _delegate: UploadTask,\n private readonly _ref: ReferenceCompat\n ) {}\n\n get snapshot(): UploadTaskSnapshotCompat {\n return new UploadTaskSnapshotCompat(\n this._delegate.snapshot,\n this,\n this._ref\n );\n }\n\n cancel = this._delegate.cancel.bind(this._delegate);\n catch = this._delegate.catch.bind(this._delegate);\n pause = this._delegate.pause.bind(this._delegate);\n resume = this._delegate.resume.bind(this._delegate);\n\n then(\n onFulfilled?: ((a: UploadTaskSnapshotCompat) => unknown) | null,\n onRejected?: ((a: StorageError) => unknown) | null\n ): Promise<unknown> {\n return this._delegate.then(snapshot => {\n if (onFulfilled) {\n return onFulfilled(\n new UploadTaskSnapshotCompat(snapshot, this, this._ref)\n );\n }\n }, onRejected);\n }\n\n on(\n type: TaskEvent,\n nextOrObserver?:\n | types.StorageObserver<UploadTaskSnapshotCompat>\n | null\n | ((a: UploadTaskSnapshotCompat) => unknown),\n error?: (error: StorageError) => void | null,\n completed?: () => void | null\n ): Unsubscribe | Subscribe<UploadTaskSnapshotCompat> {\n let wrappedNextOrObserver:\n | StorageObserver<UploadTaskSnapshot>\n | undefined\n | ((a: UploadTaskSnapshot) => unknown) = undefined;\n if (!!nextOrObserver) {\n if (typeof nextOrObserver === 'function') {\n wrappedNextOrObserver = (taskSnapshot: UploadTaskSnapshot) =>\n nextOrObserver(\n new UploadTaskSnapshotCompat(taskSnapshot, this, this._ref)\n );\n } else {\n wrappedNextOrObserver = {\n next: !!nextOrObserver.next\n ? (taskSnapshot: UploadTaskSnapshot) =>\n nextOrObserver.next!(\n new UploadTaskSnapshotCompat(taskSnapshot, this, this._ref)\n )\n : undefined,\n complete: nextOrObserver.complete || undefined,\n error: nextOrObserver.error || undefined\n };\n }\n }\n return this._delegate.on(\n type,\n wrappedNextOrObserver,\n error || undefined,\n completed || undefined\n );\n }\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe<T> = (\n next?: NextFn<T> | StorageObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn<T> = (value: T) => void;\n\n/**\n * A function that is called with a `FirebaseStorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ListResult } from '@firebase/storage';\nimport * as types from '@firebase/storage-types';\nimport { ReferenceCompat } from './reference';\nimport { StorageServiceCompat } from './service';\nimport { Compat } from '@firebase/util';\n\nexport class ListResultCompat implements types.ListResult, Compat<ListResult> {\n constructor(\n readonly _delegate: ListResult,\n private readonly _service: StorageServiceCompat\n ) {}\n\n get prefixes(): ReferenceCompat[] {\n return this._delegate.prefixes.map(\n ref => new ReferenceCompat(ref, this._service)\n );\n }\n get items(): ReferenceCompat[] {\n return this._delegate.items.map(\n ref => new ReferenceCompat(ref, this._service)\n );\n }\n get nextPageToken(): string | null {\n return this._delegate.nextPageToken || null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n StorageReference,\n uploadBytesResumable,\n list,\n listAll,\n getDownloadURL,\n getMetadata,\n updateMetadata,\n deleteObject,\n UploadTask,\n StringFormat,\n UploadMetadata,\n FullMetadata,\n SettableMetadata,\n _UploadTask,\n _getChild,\n _Reference,\n _FbsBlob,\n _dataFromString,\n _invalidRootOperation\n} from '@firebase/storage';\n\nimport { UploadTaskCompat } from './task';\nimport { ListResultCompat } from './list';\nimport { StorageServiceCompat } from './service';\n\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class ReferenceCompat\n implements types.Reference, Compat<StorageReference>\n{\n constructor(\n readonly _delegate: StorageReference,\n public storage: StorageServiceCompat\n ) {}\n\n get name(): string {\n return this._delegate.name;\n }\n\n get bucket(): string {\n return this._delegate.bucket;\n }\n\n get fullPath(): string {\n return this._delegate.fullPath;\n }\n\n toString(): string {\n return this._delegate.toString();\n }\n\n /**\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n child(childPath: string): types.Reference {\n const reference = _getChild(this._delegate, childPath);\n return new ReferenceCompat(reference, this.storage);\n }\n\n get root(): types.Reference {\n return new ReferenceCompat(this._delegate.root, this.storage);\n }\n\n /**\n * @returns A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get parent(): types.Reference | null {\n const reference = this._delegate.parent;\n if (reference == null) {\n return null;\n }\n return new ReferenceCompat(reference, this.storage);\n }\n\n /**\n * Uploads a blob to this object's location.\n * @param data - The blob to upload.\n * @returns An UploadTask that lets you control and\n * observe the upload.\n */\n put(\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: types.FullMetadata\n ): types.UploadTask {\n this._throwIfRoot('put');\n return new UploadTaskCompat(\n uploadBytesResumable(this._delegate, data, metadata as UploadMetadata),\n this\n );\n }\n\n /**\n * Uploads a string to this object's location.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @returns An UploadTask that lets you control and\n * observe the upload.\n */\n putString(\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: types.UploadMetadata\n ): types.UploadTask {\n this._throwIfRoot('putString');\n const data = _dataFromString(format, value);\n const metadataClone = { ...metadata };\n if (metadataClone['contentType'] == null && data.contentType != null) {\n metadataClone['contentType'] = data.contentType;\n }\n return new UploadTaskCompat(\n new _UploadTask(\n this._delegate as _Reference,\n new _FbsBlob(data.data, true),\n metadataClone as FullMetadata & { [k: string]: string }\n ) as UploadTask,\n this\n );\n }\n\n /**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: listAll may potentially consume too many resources if there are\n * too many results.\n *\n * @returns A Promise that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\n listAll(): Promise<types.ListResult> {\n return listAll(this._delegate).then(\n r => new ListResultCompat(r, this.storage)\n );\n }\n\n /**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure. Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n *\n * @param options - See ListOptions for details.\n * @returns A Promise that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\n list(options?: types.ListOptions | null): Promise<types.ListResult> {\n return list(this._delegate, options || undefined).then(\n r => new ListResultCompat(r, this.storage)\n );\n }\n\n /**\n * A `Promise` that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n getMetadata(): Promise<types.FullMetadata> {\n return getMetadata(this._delegate) as Promise<types.FullMetadata>;\n }\n\n /**\n * Updates the metadata for this object.\n * @param metadata - The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @returns A `Promise` that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n updateMetadata(\n metadata: types.SettableMetadata\n ): Promise<types.FullMetadata> {\n return updateMetadata(\n this._delegate,\n metadata as SettableMetadata\n ) as Promise<types.FullMetadata>;\n }\n\n /**\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\n getDownloadURL(): Promise<string> {\n return getDownloadURL(this._delegate);\n }\n\n /**\n * Deletes the object at this location.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\n delete(): Promise<void> {\n this._throwIfRoot('delete');\n return deleteObject(this._delegate);\n }\n\n private _throwIfRoot(name: string): void {\n if ((this._delegate as _Reference)._location.path === '') {\n throw _invalidRootOperation(name);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as types from '@firebase/storage-types';\nimport { FirebaseApp } from '@firebase/app-types';\n\nimport {\n ref,\n connectStorageEmulator,\n FirebaseStorage,\n _Location,\n _invalidArgument,\n _FirebaseStorageImpl\n} from '@firebase/storage';\nimport { ReferenceCompat } from './reference';\nimport { Compat, EmulatorMockTokenOptions } from '@firebase/util';\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n */\nexport class StorageServiceCompat\n implements types.FirebaseStorage, Compat<FirebaseStorage>\n{\n constructor(public app: FirebaseApp, readonly _delegate: FirebaseStorage) {}\n\n get maxOperationRetryTime(): number {\n return this._delegate.maxOperationRetryTime;\n }\n\n get maxUploadRetryTime(): number {\n return this._delegate.maxUploadRetryTime;\n }\n\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n ref(path?: string): types.Reference {\n if (isUrl(path)) {\n throw _invalidArgument(\n 'ref() expected a child path but got a URL, use refFromURL instead.'\n );\n }\n return new ReferenceCompat(ref(this._delegate, path), this);\n }\n\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n refFromURL(url: string): types.Reference {\n if (!isUrl(url)) {\n throw _invalidArgument(\n 'refFromURL() expected a full URL but got a child path, use ref() instead.'\n );\n }\n try {\n _Location.makeFromUrl(url, (this._delegate as _FirebaseStorageImpl).host);\n } catch (e) {\n throw _invalidArgument(\n 'refFromUrl() expected a valid full URL but got an invalid one.'\n );\n }\n return new ReferenceCompat(ref(this._delegate, url), this);\n }\n\n setMaxUploadRetryTime(time: number): void {\n this._delegate.maxUploadRetryTime = time;\n }\n\n setMaxOperationRetryTime(time: number): void {\n this._delegate.maxOperationRetryTime = time;\n }\n\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n ): void {\n connectStorageEmulator(this._delegate, host, port, options);\n }\n}\n\nfunction isUrl(path?: string): boolean {\n return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { version } from '../package.json';\n\nexport const SDK_VERSION = version;\n/** The prefix for start User Timing marks used for creating Traces. */\nexport const TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';\n/** The prefix for stop User Timing marks used for creating Traces. */\nexport const TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';\n/** The prefix for User Timing measure used for creating Traces. */\nexport const TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';\n/** The prefix for out of the box page load Trace name. */\nexport const OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';\n\nexport const FIRST_PAINT_COUNTER_NAME = '_fp';\n\nexport const FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';\n\nexport const FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';\n\nexport const CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';\n\nexport const CONFIG_EXPIRY_LOCAL_STORAGE_KEY =\n '@firebase/performance/configexpire';\n\nexport const SERVICE = 'performance';\nexport const SERVICE_NAME = 'Performance';\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Api } from '../services/api_service';\n\n// The values and orders of the following enums should not be changed.\nconst enum ServiceWorkerStatus {\n UNKNOWN = 0,\n UNSUPPORTED = 1,\n CONTROLLED = 2,\n UNCONTROLLED = 3\n}\n\nexport enum VisibilityState {\n UNKNOWN = 0,\n VISIBLE = 1,\n HIDDEN = 2\n}\n\nconst enum EffectiveConnectionType {\n UNKNOWN = 0,\n CONNECTION_SLOW_2G = 1,\n CONNECTION_2G = 2,\n CONNECTION_3G = 3,\n CONNECTION_4G = 4\n}\n\n/**\n * NetworkInformation\n *\n * ref: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation\n */\ninterface NetworkInformationWithEffectiveType extends NetworkInformation {\n // `effectiveType` is an experimental property and not included in\n // TypeScript's typings for the native NetworkInformation interface\n readonly effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';\n}\n\ninterface NavigatorWithConnection extends Navigator {\n readonly connection: NetworkInformationWithEffectiveType;\n}\n\nconst RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_'];\nconst ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\\\w*$');\nconst MAX_ATTRIBUTE_NAME_LENGTH = 40;\nconst MAX_ATTRIBUTE_VALUE_LENGTH = 100;\n\nexport function getServiceWorkerStatus(): ServiceWorkerStatus {\n const navigator = Api.getInstance().navigator;\n if (navigator?.serviceWorker) {\n if (navigator.serviceWorker.controller) {\n return ServiceWorkerStatus.CONTROLLED;\n } else {\n return ServiceWorkerStatus.UNCONTROLLED;\n }\n } else {\n return ServiceWorkerStatus.UNSUPPORTED;\n }\n}\n\nexport function getVisibilityState(): VisibilityState {\n const document = Api.getInstance().document;\n const visibilityState = document.visibilityState;\n switch (visibilityState) {\n case 'visible':\n return VisibilityState.VISIBLE;\n case 'hidden':\n return VisibilityState.HIDDEN;\n default:\n return VisibilityState.UNKNOWN;\n }\n}\n\nexport function getEffectiveConnectionType(): EffectiveConnectionType {\n const navigator = Api.getInstance().navigator;\n const navigatorConnection = (navigator as NavigatorWithConnection).connection;\n const effectiveType =\n navigatorConnection && navigatorConnection.effectiveType;\n switch (effectiveType) {\n case 'slow-2g':\n return EffectiveConnectionType.CONNECTION_SLOW_2G;\n case '2g':\n return EffectiveConnectionType.CONNECTION_2G;\n case '3g':\n return EffectiveConnectionType.CONNECTION_3G;\n case '4g':\n return EffectiveConnectionType.CONNECTION_4G;\n default:\n return EffectiveConnectionType.UNKNOWN;\n }\n}\n\nexport function isValidCustomAttributeName(name: string): boolean {\n if (name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) {\n return false;\n }\n const matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(prefix =>\n name.startsWith(prefix)\n );\n return !matchesReservedPrefix && !!name.match(ATTRIBUTE_FORMAT_REGEX);\n}\n\nexport function isValidCustomAttributeValue(value: string): boolean {\n return value.length !== 0 && value.length <= MAX_ATTRIBUTE_VALUE_LENGTH;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport {\n Component,\n ComponentContainer,\n ComponentType\n} from '@firebase/component';\nimport { PerformanceCompatImpl } from './performance';\nimport { name as packageName, version } from '../package.json';\nimport { FirebasePerformance as FirebasePerformanceCompat } from '@firebase/performance-types';\n\nfunction registerPerformanceCompat(firebaseInstance: _FirebaseNamespace): void {\n firebaseInstance.INTERNAL.registerComponent(\n new Component(\n 'performance-compat',\n performanceFactory,\n ComponentType.PUBLIC\n )\n );\n\n firebaseInstance.registerVersion(packageName, version);\n}\n\nfunction performanceFactory(\n container: ComponentContainer\n): PerformanceCompatImpl {\n const app = container.getProvider('app-compat').getImmediate();\n // The following call will always succeed.\n const performance = container.getProvider('performance').getImmediate();\n\n return new PerformanceCompatImpl(app, performance);\n}\n\nregisterPerformanceCompat(firebase as _FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n performance: {\n (app?: FirebaseApp): FirebasePerformanceCompat;\n };\n }\n interface FirebaseApp {\n performance(): FirebasePerformanceCompat;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { RemoteConfigCompatImpl, isSupported } from './remoteConfig';\nimport { name as packageName, version } from '../package.json';\nimport { RemoteConfig as RemoteConfigCompat } from '@firebase/remote-config-types';\n\nfunction registerRemoteConfigCompat(\n firebaseInstance: _FirebaseNamespace\n): void {\n firebaseInstance.INTERNAL.registerComponent(\n new Component(\n 'remoteConfig-compat',\n remoteConfigFactory,\n ComponentType.PUBLIC\n )\n .setMultipleInstances(true)\n .setServiceProps({ isSupported })\n );\n\n firebaseInstance.registerVersion(packageName, version);\n}\n\nfunction remoteConfigFactory(\n container: ComponentContainer,\n { instanceIdentifier: namespace }: InstanceFactoryOptions\n): RemoteConfigCompatImpl {\n const app = container.getProvider('app-compat').getImmediate();\n // The following call will always succeed because rc `import {...} from '@firebase/remote-config'`\n const remoteConfig = container.getProvider('remote-config').getImmediate({\n identifier: namespace\n });\n\n return new RemoteConfigCompatImpl(app, remoteConfig);\n}\n\nregisterRemoteConfigCompat(firebase as _FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n remoteConfig: {\n (app?: FirebaseApp): RemoteConfigCompat;\n };\n }\n interface FirebaseApp {\n remoteConfig(): RemoteConfigCompat;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from '../constants';\n\nexport const enum ErrorCode {\n TRACE_STARTED_BEFORE = 'trace started',\n TRACE_STOPPED_BEFORE = 'trace stopped',\n NONPOSITIVE_TRACE_START_TIME = 'nonpositive trace startTime',\n NONPOSITIVE_TRACE_DURATION = 'nonpositive trace duration',\n NO_WINDOW = 'no window',\n NO_APP_ID = 'no app id',\n NO_PROJECT_ID = 'no project id',\n NO_API_KEY = 'no api key',\n INVALID_CC_LOG = 'invalid cc log',\n FB_NOT_DEFAULT = 'FB not default',\n RC_NOT_OK = 'RC response not ok',\n INVALID_ATTRIBUTE_NAME = 'invalid attribute name',\n INVALID_ATTRIBUTE_VALUE = 'invalid attribute value',\n INVALID_CUSTOM_METRIC_NAME = 'invalid custom metric name',\n INVALID_STRING_MERGER_PARAMETER = 'invalid String merger input',\n ALREADY_INITIALIZED = 'already initialized'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.TRACE_STARTED_BEFORE]: 'Trace {$traceName} was started before.',\n [ErrorCode.TRACE_STOPPED_BEFORE]: 'Trace {$traceName} is not running.',\n [ErrorCode.NONPOSITIVE_TRACE_START_TIME]:\n 'Trace {$traceName} startTime should be positive.',\n [ErrorCode.NONPOSITIVE_TRACE_DURATION]:\n 'Trace {$traceName} duration should be positive.',\n [ErrorCode.NO_WINDOW]: 'Window is not available.',\n [ErrorCode.NO_APP_ID]: 'App id is not available.',\n [ErrorCode.NO_PROJECT_ID]: 'Project id is not available.',\n [ErrorCode.NO_API_KEY]: 'Api key is not available.',\n [ErrorCode.INVALID_CC_LOG]: 'Attempted to queue invalid cc event',\n [ErrorCode.FB_NOT_DEFAULT]:\n 'Performance can only start when Firebase app instance is the default one.',\n [ErrorCode.RC_NOT_OK]: 'RC response is not ok',\n [ErrorCode.INVALID_ATTRIBUTE_NAME]:\n 'Attribute name {$attributeName} is invalid.',\n [ErrorCode.INVALID_ATTRIBUTE_VALUE]:\n 'Attribute value {$attributeValue} is invalid.',\n [ErrorCode.INVALID_CUSTOM_METRIC_NAME]:\n 'Custom metric name {$customMetricName} is invalid',\n [ErrorCode.INVALID_STRING_MERGER_PARAMETER]:\n 'Input for String merger is invalid, contact support team to resolve.',\n [ErrorCode.ALREADY_INITIALIZED]:\n 'initializePerformance() has already been called with ' +\n 'different options. To avoid this error, call initializePerformance() with the ' +\n 'same options as when it was originally called, or call getPerformance() to return the' +\n ' already initialized instance.'\n};\n\ninterface ErrorParams {\n [ErrorCode.TRACE_STARTED_BEFORE]: { traceName: string };\n [ErrorCode.TRACE_STOPPED_BEFORE]: { traceName: string };\n [ErrorCode.NONPOSITIVE_TRACE_START_TIME]: { traceName: string };\n [ErrorCode.NONPOSITIVE_TRACE_DURATION]: { traceName: string };\n [ErrorCode.INVALID_ATTRIBUTE_NAME]: { attributeName: string };\n [ErrorCode.INVALID_ATTRIBUTE_VALUE]: { attributeValue: string };\n [ErrorCode.INVALID_CUSTOM_METRIC_NAME]: { customMetricName: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SERVICE_NAME } from '../constants';\n\nexport const consoleLogger = new Logger(SERVICE_NAME);\nconsoleLogger.logLevel = LogLevel.INFO;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport { isIndexedDBAvailable, areCookiesEnabled } from '@firebase/util';\nimport { consoleLogger } from '../utils/console_logger';\n\ndeclare global {\n interface Window {\n PerformanceObserver: typeof PerformanceObserver;\n perfMetrics?: { onFirstInputDelay(fn: (fid: number) => void): void };\n }\n}\n\nlet apiInstance: Api | undefined;\nlet windowInstance: Window | undefined;\n\nexport type EntryType =\n | 'mark'\n | 'measure'\n | 'paint'\n | 'resource'\n | 'frame'\n | 'navigation';\n\n/**\n * This class holds a reference to various browser related objects injected by\n * set methods.\n */\nexport class Api {\n private readonly performance: Performance;\n /** PreformanceObserver constructor function. */\n private readonly PerformanceObserver: typeof PerformanceObserver;\n private readonly windowLocation: Location;\n readonly onFirstInputDelay?: (fn: (fid: number) => void) => void;\n readonly localStorage?: Storage;\n readonly document: Document;\n readonly navigator: Navigator;\n\n constructor(readonly window?: Window) {\n if (!window) {\n throw ERROR_FACTORY.create(ErrorCode.NO_WINDOW);\n }\n this.performance = window.performance;\n this.PerformanceObserver = window.PerformanceObserver;\n this.windowLocation = window.location;\n this.navigator = window.navigator;\n this.document = window.document;\n if (this.navigator && this.navigator.cookieEnabled) {\n // If user blocks cookies on the browser, accessing localStorage will\n // throw an exception.\n this.localStorage = window.localStorage;\n }\n if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) {\n this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay;\n }\n }\n\n getUrl(): string {\n // Do not capture the string query part of url.\n return this.windowLocation.href.split('?')[0];\n }\n\n mark(name: string): void {\n if (!this.performance || !this.performance.mark) {\n return;\n }\n this.performance.mark(name);\n }\n\n measure(measureName: string, mark1: string, mark2: string): void {\n if (!this.performance || !this.performance.measure) {\n return;\n }\n this.performance.measure(measureName, mark1, mark2);\n }\n\n getEntriesByType(type: EntryType): PerformanceEntry[] {\n if (!this.performance || !this.performance.getEntriesByType) {\n return [];\n }\n return this.performance.getEntriesByType(type);\n }\n\n getEntriesByName(name: string): PerformanceEntry[] {\n if (!this.performance || !this.performance.getEntriesByName) {\n return [];\n }\n return this.performance.getEntriesByName(name);\n }\n\n getTimeOrigin(): number {\n // Polyfill the time origin with performance.timing.navigationStart.\n return (\n this.performance &&\n (this.performance.timeOrigin || this.performance.timing.navigationStart)\n );\n }\n\n requiredApisAvailable(): boolean {\n if (!fetch || !Promise || !areCookiesEnabled()) {\n consoleLogger.info(\n 'Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.'\n );\n return false;\n }\n\n if (!isIndexedDBAvailable()) {\n consoleLogger.info('IndexedDB is not supported by current browswer');\n return false;\n }\n return true;\n }\n\n setupObserver(\n entryType: EntryType,\n callback: (entry: PerformanceEntry) => void\n ): void {\n if (!this.PerformanceObserver) {\n return;\n }\n const observer = new this.PerformanceObserver(list => {\n for (const entry of list.getEntries()) {\n // `entry` is a PerformanceEntry instance.\n callback(entry);\n }\n });\n\n // Start observing the entry types you care about.\n observer.observe({ entryTypes: [entryType] });\n }\n\n static getInstance(): Api {\n if (apiInstance === undefined) {\n apiInstance = new Api(windowInstance);\n }\n return apiInstance;\n }\n}\n\nexport function setupApi(window: Window): void {\n windowInstance = window;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\n\nlet iid: string | undefined;\nlet authToken: string | undefined;\n\nexport function getIidPromise(\n installationsService: _FirebaseInstallationsInternal\n): Promise<string> {\n const iidPromise = installationsService.getId();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n iidPromise.then((iidVal: string) => {\n iid = iidVal;\n });\n return iidPromise;\n}\n\n// This method should be used after the iid is retrieved by getIidPromise method.\nexport function getIid(): string | undefined {\n return iid;\n}\n\nexport function getAuthTokenPromise(\n installationsService: _FirebaseInstallationsInternal\n): Promise<string> {\n const authTokenPromise = installationsService.getToken();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n authTokenPromise.then((authTokenVal: string) => {\n authToken = authTokenVal;\n });\n return authTokenPromise;\n}\n\nexport function getAuthenticationToken(): string | undefined {\n return authToken;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from './errors';\n\nexport function mergeStrings(part1: string, part2: string): string {\n const sizeDiff = part1.length - part2.length;\n if (sizeDiff < 0 || sizeDiff > 1) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_STRING_MERGER_PARAMETER);\n }\n\n const resultArray = [];\n for (let i = 0; i < part1.length; i++) {\n resultArray.push(part1.charAt(i));\n if (part2.length > i) {\n resultArray.push(part2.charAt(i));\n }\n }\n\n return resultArray.join('');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { mergeStrings } from '../utils/string_merger';\n\nlet settingsServiceInstance: SettingsService | undefined;\n\nexport class SettingsService {\n // The variable which controls logging of automatic traces and HTTP/S network monitoring.\n instrumentationEnabled = true;\n\n // The variable which controls logging of custom traces.\n dataCollectionEnabled = true;\n\n // Configuration flags set through remote config.\n loggingEnabled = false;\n // Sampling rate between 0 and 1.\n tracesSamplingRate = 1;\n networkRequestsSamplingRate = 1;\n\n // Address of logging service.\n logEndPointUrl =\n 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto';\n // Performance event transport endpoint URL which should be compatible with proto3.\n // New Address for transport service, not configurable via Remote Config.\n flTransportEndpointUrl = mergeStrings(\n 'hts/frbslgigp.ogepscmv/ieo/eaylg',\n 'tp:/ieaeogn-agolai.o/1frlglgc/o'\n );\n\n transportKey = mergeStrings('AzSC8r6ReiGqFMyfvgow', 'Iayx0u-XT3vksVM-pIV');\n\n // Source type for performance event logs.\n logSource = 462;\n\n // Flags which control per session logging of traces and network requests.\n logTraceAfterSampling = false;\n logNetworkAfterSampling = false;\n\n // TTL of config retrieved from remote config in hours.\n configTimeToLive = 12;\n\n getFlTransportFullUrl(): string {\n return this.flTransportEndpointUrl.concat('?key=', this.transportKey);\n }\n\n static getInstance(): SettingsService {\n if (settingsServiceInstance === undefined) {\n settingsServiceInstance = new SettingsService();\n }\n return settingsServiceInstance;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getAppId(firebaseApp: FirebaseApp): string {\n const appId = firebaseApp.options?.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(ErrorCode.NO_APP_ID);\n }\n return appId;\n}\n\nexport function getProjectId(firebaseApp: FirebaseApp): string {\n const projectId = firebaseApp.options?.projectId;\n if (!projectId) {\n throw ERROR_FACTORY.create(ErrorCode.NO_PROJECT_ID);\n }\n return projectId;\n}\n\nexport function getApiKey(firebaseApp: FirebaseApp): string {\n const apiKey = firebaseApp.options?.apiKey;\n if (!apiKey) {\n throw ERROR_FACTORY.create(ErrorCode.NO_API_KEY);\n }\n return apiKey;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CONFIG_EXPIRY_LOCAL_STORAGE_KEY,\n CONFIG_LOCAL_STORAGE_KEY,\n SDK_VERSION\n} from '../constants';\nimport { consoleLogger } from '../utils/console_logger';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\n\nimport { Api } from './api_service';\nimport { getAuthTokenPromise } from './iid_service';\nimport { SettingsService } from './settings_service';\nimport { PerformanceController } from '../controllers/perf';\nimport { getProjectId, getApiKey, getAppId } from '../utils/app_utils';\n\nconst REMOTE_CONFIG_SDK_VERSION = '0.0.1';\n\ninterface SecondaryConfig {\n loggingEnabled?: boolean;\n logSource?: number;\n logEndPointUrl?: string;\n transportKey?: string;\n tracesSamplingRate?: number;\n networkRequestsSamplingRate?: number;\n}\n\n// These values will be used if the remote config object is successfully\n// retrieved, but the template does not have these fields.\nconst DEFAULT_CONFIGS: SecondaryConfig = {\n loggingEnabled: true\n};\n\n/* eslint-disable camelcase */\ninterface RemoteConfigTemplate {\n fpr_enabled?: string;\n fpr_log_source?: string;\n fpr_log_endpoint_url?: string;\n fpr_log_transport_key?: string;\n fpr_log_transport_web_percent?: string;\n fpr_vc_network_request_sampling_rate?: string;\n fpr_vc_trace_sampling_rate?: string;\n fpr_vc_session_sampling_rate?: string;\n}\n/* eslint-enable camelcase */\n\ninterface RemoteConfigResponse {\n entries?: RemoteConfigTemplate;\n state?: string;\n}\n\nconst FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';\n\nexport function getConfig(\n performanceController: PerformanceController,\n iid: string\n): Promise<void> {\n const config = getStoredConfig();\n if (config) {\n processConfig(config);\n return Promise.resolve();\n }\n\n return getRemoteConfig(performanceController, iid)\n .then(processConfig)\n .then(\n config => storeConfig(config),\n /** Do nothing for error, use defaults set in settings service. */\n () => {}\n );\n}\n\nfunction getStoredConfig(): RemoteConfigResponse | undefined {\n const localStorage = Api.getInstance().localStorage;\n if (!localStorage) {\n return;\n }\n const expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);\n if (!expiryString || !configValid(expiryString)) {\n return;\n }\n\n const configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);\n if (!configStringified) {\n return;\n }\n try {\n const configResponse: RemoteConfigResponse = JSON.parse(configStringified);\n return configResponse;\n } catch {\n return;\n }\n}\n\nfunction storeConfig(config: RemoteConfigResponse | undefined): void {\n const localStorage = Api.getInstance().localStorage;\n if (!config || !localStorage) {\n return;\n }\n\n localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));\n localStorage.setItem(\n CONFIG_EXPIRY_LOCAL_STORAGE_KEY,\n String(\n Date.now() +\n SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000\n )\n );\n}\n\nconst COULD_NOT_GET_CONFIG_MSG =\n 'Could not fetch config, will use default configs';\n\nfunction getRemoteConfig(\n performanceController: PerformanceController,\n iid: string\n): Promise<RemoteConfigResponse | undefined> {\n // Perf needs auth token only to retrieve remote config.\n return getAuthTokenPromise(performanceController.installations)\n .then(authToken => {\n const projectId = getProjectId(performanceController.app);\n const apiKey = getApiKey(performanceController.app);\n const configEndPoint = `https://firebaseremoteconfig.googleapis.com/v1/projects/${projectId}/namespaces/fireperf:fetch?key=${apiKey}`;\n const request = new Request(configEndPoint, {\n method: 'POST',\n headers: { Authorization: `${FIS_AUTH_PREFIX} ${authToken}` },\n /* eslint-disable camelcase */\n body: JSON.stringify({\n app_instance_id: iid,\n app_instance_id_token: authToken,\n app_id: getAppId(performanceController.app),\n app_version: SDK_VERSION,\n sdk_version: REMOTE_CONFIG_SDK_VERSION\n })\n /* eslint-enable camelcase */\n });\n return fetch(request).then(response => {\n if (response.ok) {\n return response.json() as RemoteConfigResponse;\n }\n // In case response is not ok. This will be caught by catch.\n throw ERROR_FACTORY.create(ErrorCode.RC_NOT_OK);\n });\n })\n .catch(() => {\n consoleLogger.info(COULD_NOT_GET_CONFIG_MSG);\n return undefined;\n });\n}\n\n/**\n * Processes config coming either from calling RC or from local storage.\n * This method only runs if call is successful or config in storage\n * is valid.\n */\nfunction processConfig(\n config?: RemoteConfigResponse\n): RemoteConfigResponse | undefined {\n if (!config) {\n return config;\n }\n const settingsServiceInstance = SettingsService.getInstance();\n const entries = config.entries || {};\n if (entries.fpr_enabled !== undefined) {\n // TODO: Change the assignment of loggingEnabled once the received type is\n // known.\n settingsServiceInstance.loggingEnabled =\n String(entries.fpr_enabled) === 'true';\n } else if (DEFAULT_CONFIGS.loggingEnabled !== undefined) {\n // Config retrieved successfully, but there is no fpr_enabled in template.\n // Use secondary configs value.\n settingsServiceInstance.loggingEnabled = DEFAULT_CONFIGS.loggingEnabled;\n }\n if (entries.fpr_log_source) {\n settingsServiceInstance.logSource = Number(entries.fpr_log_source);\n } else if (DEFAULT_CONFIGS.logSource) {\n settingsServiceInstance.logSource = DEFAULT_CONFIGS.logSource;\n }\n\n if (entries.fpr_log_endpoint_url) {\n settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url;\n } else if (DEFAULT_CONFIGS.logEndPointUrl) {\n settingsServiceInstance.logEndPointUrl = DEFAULT_CONFIGS.logEndPointUrl;\n }\n\n // Key from Remote Config has to be non-empty string, otherwsie use local value.\n if (entries.fpr_log_transport_key) {\n settingsServiceInstance.transportKey = entries.fpr_log_transport_key;\n } else if (DEFAULT_CONFIGS.transportKey) {\n settingsServiceInstance.transportKey = DEFAULT_CONFIGS.transportKey;\n }\n\n if (entries.fpr_vc_network_request_sampling_rate !== undefined) {\n settingsServiceInstance.networkRequestsSamplingRate = Number(\n entries.fpr_vc_network_request_sampling_rate\n );\n } else if (DEFAULT_CONFIGS.networkRequestsSamplingRate !== undefined) {\n settingsServiceInstance.networkRequestsSamplingRate =\n DEFAULT_CONFIGS.networkRequestsSamplingRate;\n }\n if (entries.fpr_vc_trace_sampling_rate !== undefined) {\n settingsServiceInstance.tracesSamplingRate = Number(\n entries.fpr_vc_trace_sampling_rate\n );\n } else if (DEFAULT_CONFIGS.tracesSamplingRate !== undefined) {\n settingsServiceInstance.tracesSamplingRate =\n DEFAULT_CONFIGS.tracesSamplingRate;\n }\n // Set the per session trace and network logging flags.\n settingsServiceInstance.logTraceAfterSampling = shouldLogAfterSampling(\n settingsServiceInstance.tracesSamplingRate\n );\n settingsServiceInstance.logNetworkAfterSampling = shouldLogAfterSampling(\n settingsServiceInstance.networkRequestsSamplingRate\n );\n return config;\n}\n\nfunction configValid(expiry: string): boolean {\n return Number(expiry) > Date.now();\n}\n\nfunction shouldLogAfterSampling(samplingRate: number): boolean {\n return Math.random() <= samplingRate;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getIidPromise } from './iid_service';\nimport { getConfig } from './remote_config_service';\nimport { Api } from './api_service';\nimport { PerformanceController } from '../controllers/perf';\n\nconst enum InitializationStatus {\n notInitialized = 1,\n initializationPending,\n initialized\n}\n\nlet initializationStatus = InitializationStatus.notInitialized;\n\nlet initializationPromise: Promise<void> | undefined;\n\nexport function getInitializationPromise(\n performanceController: PerformanceController\n): Promise<void> {\n initializationStatus = InitializationStatus.initializationPending;\n\n initializationPromise =\n initializationPromise || initializePerf(performanceController);\n\n return initializationPromise;\n}\n\nexport function isPerfInitialized(): boolean {\n return initializationStatus === InitializationStatus.initialized;\n}\n\nfunction initializePerf(\n performanceController: PerformanceController\n): Promise<void> {\n return getDocumentReadyComplete()\n .then(() => getIidPromise(performanceController.installations))\n .then(iid => getConfig(performanceController, iid))\n .then(\n () => changeInitializationStatus(),\n () => changeInitializationStatus()\n );\n}\n\n/**\n * Returns a promise which resolves whenever the document readystate is complete or\n * immediately if it is called after page load complete.\n */\nfunction getDocumentReadyComplete(): Promise<void> {\n const document = Api.getInstance().document;\n return new Promise(resolve => {\n if (document && document.readyState !== 'complete') {\n const handler = (): void => {\n if (document.readyState === 'complete') {\n document.removeEventListener('readystatechange', handler);\n resolve();\n }\n };\n document.addEventListener('readystatechange', handler);\n } else {\n resolve();\n }\n });\n}\n\nfunction changeInitializationStatus(): void {\n initializationStatus = InitializationStatus.initialized;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SettingsService } from './settings_service';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport { consoleLogger } from '../utils/console_logger';\n\nconst DEFAULT_SEND_INTERVAL_MS = 10 * 1000;\nconst INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;\n// If end point does not work, the call will be tried for these many times.\nconst DEFAULT_REMAINING_TRIES = 3;\nconst MAX_EVENT_COUNT_PER_REQUEST = 1000;\nlet remainingTries = DEFAULT_REMAINING_TRIES;\n\ninterface LogResponseDetails {\n responseAction?: string;\n}\n\ninterface BatchEvent {\n message: string;\n eventTime: number;\n}\n\n/* eslint-disable camelcase */\n// CC/Fl accepted log format.\ninterface TransportBatchLogFormat {\n request_time_ms: string;\n client_info: ClientInfo;\n log_source: number;\n log_event: Log[];\n}\n\ninterface ClientInfo {\n client_type: number;\n js_client_info: {};\n}\n\ninterface Log {\n source_extension_json_proto3: string;\n event_time_ms: string;\n}\n/* eslint-enable camelcase */\n\nlet queue: BatchEvent[] = [];\n\nlet isTransportSetup: boolean = false;\n\nexport function setupTransportService(): void {\n if (!isTransportSetup) {\n processQueue(INITIAL_SEND_TIME_DELAY_MS);\n isTransportSetup = true;\n }\n}\n\n/**\n * Utilized by testing to clean up message queue and un-initialize transport service.\n */\nexport function resetTransportService(): void {\n isTransportSetup = false;\n queue = [];\n}\n\nfunction processQueue(timeOffset: number): void {\n setTimeout(() => {\n // If there is no remainingTries left, stop retrying.\n if (remainingTries === 0) {\n return;\n }\n\n // If there are no events to process, wait for DEFAULT_SEND_INTERVAL_MS and try again.\n if (!queue.length) {\n return processQueue(DEFAULT_SEND_INTERVAL_MS);\n }\n\n dispatchQueueEvents();\n }, timeOffset);\n}\n\nfunction dispatchQueueEvents(): void {\n // Extract events up to the maximum cap of single logRequest from top of \"official queue\".\n // The staged events will be used for current logRequest attempt, remaining events will be kept\n // for next attempt.\n const staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST);\n\n /* eslint-disable camelcase */\n // We will pass the JSON serialized event to the backend.\n const log_event: Log[] = staged.map(evt => ({\n source_extension_json_proto3: evt.message,\n event_time_ms: String(evt.eventTime)\n }));\n\n const data: TransportBatchLogFormat = {\n request_time_ms: String(Date.now()),\n client_info: {\n client_type: 1, // 1 is JS\n js_client_info: {}\n },\n log_source: SettingsService.getInstance().logSource,\n log_event\n };\n /* eslint-enable camelcase */\n\n sendEventsToFl(data, staged).catch(() => {\n // If the request fails for some reason, add the events that were attempted\n // back to the primary queue to retry later.\n queue = [...staged, ...queue];\n remainingTries--;\n consoleLogger.info(`Tries left: ${remainingTries}.`);\n processQueue(DEFAULT_SEND_INTERVAL_MS);\n });\n}\n\nfunction sendEventsToFl(\n data: TransportBatchLogFormat,\n staged: BatchEvent[]\n): Promise<void> {\n return postToFlEndpoint(data)\n .then(res => {\n if (!res.ok) {\n consoleLogger.info('Call to Firebase backend failed.');\n }\n return res.json();\n })\n .then(res => {\n // Find the next call wait time from the response.\n const transportWait = Number(res.nextRequestWaitMillis);\n let requestOffset = DEFAULT_SEND_INTERVAL_MS;\n if (!isNaN(transportWait)) {\n requestOffset = Math.max(transportWait, requestOffset);\n }\n\n // Delete request if response include RESPONSE_ACTION_UNKNOWN or DELETE_REQUEST action.\n // Otherwise, retry request using normal scheduling if response include RETRY_REQUEST_LATER.\n const logResponseDetails: LogResponseDetails[] = res.logResponseDetails;\n if (\n Array.isArray(logResponseDetails) &&\n logResponseDetails.length > 0 &&\n logResponseDetails[0].responseAction === 'RETRY_REQUEST_LATER'\n ) {\n queue = [...staged, ...queue];\n consoleLogger.info(`Retry transport request later.`);\n }\n\n remainingTries = DEFAULT_REMAINING_TRIES;\n // Schedule the next process.\n processQueue(requestOffset);\n });\n}\n\nfunction postToFlEndpoint(data: TransportBatchLogFormat): Promise<Response> {\n const flTransportFullUrl =\n SettingsService.getInstance().getFlTransportFullUrl();\n return fetch(flTransportFullUrl, {\n method: 'POST',\n body: JSON.stringify(data)\n });\n}\n\nfunction addToQueue(evt: BatchEvent): void {\n if (!evt.eventTime || !evt.message) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_CC_LOG);\n }\n // Add the new event to the queue.\n queue = [...queue, evt];\n}\n\n/** Log handler for cc service to send the performance logs to the server. */\nexport function transportHandler(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serializer: (...args: any[]) => string\n): (...args: unknown[]) => void {\n return (...args) => {\n const message = serializer(...args);\n addToQueue({\n message,\n eventTime: Date.now()\n });\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getIid } from './iid_service';\nimport { NetworkRequest } from '../resources/network_request';\nimport { Trace } from '../resources/trace';\nimport { Api } from './api_service';\nimport { SettingsService } from './settings_service';\nimport {\n getServiceWorkerStatus,\n getVisibilityState,\n VisibilityState,\n getEffectiveConnectionType\n} from '../utils/attributes_utils';\nimport {\n isPerfInitialized,\n getInitializationPromise\n} from './initialization_service';\nimport { transportHandler } from './transport_service';\nimport { SDK_VERSION } from '../constants';\nimport { FirebaseApp } from '@firebase/app';\nimport { getAppId } from '../utils/app_utils';\n\nconst enum ResourceType {\n NetworkRequest,\n Trace\n}\n\n/* eslint-disable camelcase */\ninterface ApplicationInfo {\n google_app_id: string;\n app_instance_id?: string;\n web_app_info: WebAppInfo;\n application_process_state: number;\n}\n\ninterface WebAppInfo {\n sdk_version: string;\n page_url: string;\n service_worker_status: number;\n visibility_state: number;\n effective_connection_type: number;\n}\n\ninterface PerfNetworkLog {\n application_info: ApplicationInfo;\n network_request_metric: NetworkRequestMetric;\n}\n\ninterface PerfTraceLog {\n application_info: ApplicationInfo;\n trace_metric: TraceMetric;\n}\n\ninterface NetworkRequestMetric {\n url: string;\n http_method: number;\n http_response_code: number;\n response_payload_bytes?: number;\n client_start_time_us?: number;\n time_to_response_initiated_us?: number;\n time_to_response_completed_us?: number;\n}\n\ninterface TraceMetric {\n name: string;\n is_auto: boolean;\n client_start_time_us: number;\n duration_us: number;\n counters?: { [key: string]: number };\n custom_attributes?: { [key: string]: string };\n}\n\n/* eslint-enble camelcase */\n\nlet logger: (\n resource: NetworkRequest | Trace,\n resourceType: ResourceType\n) => void | undefined;\n// This method is not called before initialization.\nfunction sendLog(\n resource: NetworkRequest | Trace,\n resourceType: ResourceType\n): void {\n if (!logger) {\n logger = transportHandler(serializer);\n }\n logger(resource, resourceType);\n}\n\nexport function logTrace(trace: Trace): void {\n const settingsService = SettingsService.getInstance();\n // Do not log if trace is auto generated and instrumentation is disabled.\n if (!settingsService.instrumentationEnabled && trace.isAuto) {\n return;\n }\n // Do not log if trace is custom and data collection is disabled.\n if (!settingsService.dataCollectionEnabled && !trace.isAuto) {\n return;\n }\n // Do not log if required apis are not available.\n if (!Api.getInstance().requiredApisAvailable()) {\n return;\n }\n\n // Only log the page load auto traces if page is visible.\n if (trace.isAuto && getVisibilityState() !== VisibilityState.VISIBLE) {\n return;\n }\n\n if (isPerfInitialized()) {\n sendTraceLog(trace);\n } else {\n // Custom traces can be used before the initialization but logging\n // should wait until after.\n getInitializationPromise(trace.performanceController).then(\n () => sendTraceLog(trace),\n () => sendTraceLog(trace)\n );\n }\n}\n\nfunction sendTraceLog(trace: Trace): void {\n if (!getIid()) {\n return;\n }\n\n const settingsService = SettingsService.getInstance();\n if (\n !settingsService.loggingEnabled ||\n !settingsService.logTraceAfterSampling\n ) {\n return;\n }\n\n setTimeout(() => sendLog(trace, ResourceType.Trace), 0);\n}\n\nexport function logNetworkRequest(networkRequest: NetworkRequest): void {\n const settingsService = SettingsService.getInstance();\n // Do not log network requests if instrumentation is disabled.\n if (!settingsService.instrumentationEnabled) {\n return;\n }\n\n // Do not log the js sdk's call to transport service domain to avoid unnecessary cycle.\n // Need to blacklist both old and new endpoints to avoid migration gap.\n const networkRequestUrl = networkRequest.url;\n\n // Blacklist old log endpoint and new transport endpoint.\n // Because Performance SDK doesn't instrument requests sent from SDK itself.\n const logEndpointUrl = settingsService.logEndPointUrl.split('?')[0];\n const flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0];\n if (\n networkRequestUrl === logEndpointUrl ||\n networkRequestUrl === flEndpointUrl\n ) {\n return;\n }\n\n if (\n !settingsService.loggingEnabled ||\n !settingsService.logNetworkAfterSampling\n ) {\n return;\n }\n\n setTimeout(() => sendLog(networkRequest, ResourceType.NetworkRequest), 0);\n}\n\nfunction serializer(\n resource: NetworkRequest | Trace,\n resourceType: ResourceType\n): string {\n if (resourceType === ResourceType.NetworkRequest) {\n return serializeNetworkRequest(resource as NetworkRequest);\n }\n return serializeTrace(resource as Trace);\n}\n\nfunction serializeNetworkRequest(networkRequest: NetworkRequest): string {\n const networkRequestMetric: NetworkRequestMetric = {\n url: networkRequest.url,\n http_method: networkRequest.httpMethod || 0,\n http_response_code: 200,\n response_payload_bytes: networkRequest.responsePayloadBytes,\n client_start_time_us: networkRequest.startTimeUs,\n time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs,\n time_to_response_completed_us: networkRequest.timeToResponseCompletedUs\n };\n const perfMetric: PerfNetworkLog = {\n application_info: getApplicationInfo(\n networkRequest.performanceController.app\n ),\n network_request_metric: networkRequestMetric\n };\n return JSON.stringify(perfMetric);\n}\n\nfunction serializeTrace(trace: Trace): string {\n const traceMetric: TraceMetric = {\n name: trace.name,\n is_auto: trace.isAuto,\n client_start_time_us: trace.startTimeUs,\n duration_us: trace.durationUs\n };\n\n if (Object.keys(trace.counters).length !== 0) {\n traceMetric.counters = trace.counters;\n }\n const customAttributes = trace.getAttributes();\n if (Object.keys(customAttributes).length !== 0) {\n traceMetric.custom_attributes = customAttributes;\n }\n\n const perfMetric: PerfTraceLog = {\n application_info: getApplicationInfo(trace.performanceController.app),\n trace_metric: traceMetric\n };\n return JSON.stringify(perfMetric);\n}\n\nfunction getApplicationInfo(firebaseApp: FirebaseApp): ApplicationInfo {\n return {\n google_app_id: getAppId(firebaseApp),\n app_instance_id: getIid(),\n web_app_info: {\n sdk_version: SDK_VERSION,\n page_url: Api.getInstance().getUrl(),\n service_worker_status: getServiceWorkerStatus(),\n visibility_state: getVisibilityState(),\n effective_connection_type: getEffectiveConnectionType()\n },\n application_process_state: 0\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FIRST_PAINT_COUNTER_NAME,\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n FIRST_INPUT_DELAY_COUNTER_NAME,\n OOB_TRACE_PAGE_LOAD_PREFIX\n} from '../constants';\nimport { consoleLogger } from '../utils/console_logger';\n\nconst MAX_METRIC_NAME_LENGTH = 100;\nconst RESERVED_AUTO_PREFIX = '_';\nconst oobMetrics = [\n FIRST_PAINT_COUNTER_NAME,\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n FIRST_INPUT_DELAY_COUNTER_NAME\n];\n\n/**\n * Returns true if the metric is custom and does not start with reserved prefix, or if\n * the metric is one of out of the box page load trace metrics.\n */\nexport function isValidMetricName(name: string, traceName?: string): boolean {\n if (name.length === 0 || name.length > MAX_METRIC_NAME_LENGTH) {\n return false;\n }\n return (\n (traceName &&\n traceName.startsWith(OOB_TRACE_PAGE_LOAD_PREFIX) &&\n oobMetrics.indexOf(name) > -1) ||\n !name.startsWith(RESERVED_AUTO_PREFIX)\n );\n}\n\n/**\n * Converts the provided value to an integer value to be used in case of a metric.\n * @param providedValue Provided number value of the metric that needs to be converted to an integer.\n *\n * @returns Converted integer number to be set for the metric.\n */\nexport function convertMetricValueToInteger(providedValue: number): number {\n const valueAsInteger: number = Math.floor(providedValue);\n if (valueAsInteger < providedValue) {\n consoleLogger.info(\n `Metric value should be an Integer, setting the value as : ${valueAsInteger}.`\n );\n }\n return valueAsInteger;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n TRACE_START_MARK_PREFIX,\n TRACE_STOP_MARK_PREFIX,\n TRACE_MEASURE_PREFIX,\n OOB_TRACE_PAGE_LOAD_PREFIX,\n FIRST_PAINT_COUNTER_NAME,\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n FIRST_INPUT_DELAY_COUNTER_NAME\n} from '../constants';\nimport { Api } from '../services/api_service';\nimport { logTrace } from '../services/perf_logger';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport {\n isValidCustomAttributeName,\n isValidCustomAttributeValue\n} from '../utils/attributes_utils';\nimport {\n isValidMetricName,\n convertMetricValueToInteger\n} from '../utils/metric_utils';\nimport { PerformanceTrace } from '../public_types';\nimport { PerformanceController } from '../controllers/perf';\n\nconst enum TraceState {\n UNINITIALIZED = 1,\n RUNNING,\n TERMINATED\n}\n\nexport class Trace implements PerformanceTrace {\n private state: TraceState = TraceState.UNINITIALIZED;\n startTimeUs!: number;\n durationUs!: number;\n private customAttributes: { [key: string]: string } = {};\n counters: { [counterName: string]: number } = {};\n private api = Api.getInstance();\n private randomId = Math.floor(Math.random() * 1000000);\n private traceStartMark!: string;\n private traceStopMark!: string;\n private traceMeasure!: string;\n\n /**\n * @param performanceController The performance controller running.\n * @param name The name of the trace.\n * @param isAuto If the trace is auto-instrumented.\n * @param traceMeasureName The name of the measure marker in user timing specification. This field\n * is only set when the trace is built for logging when the user directly uses the user timing\n * api (performance.mark and performance.measure).\n */\n constructor(\n readonly performanceController: PerformanceController,\n readonly name: string,\n readonly isAuto = false,\n traceMeasureName?: string\n ) {\n if (!this.isAuto) {\n this.traceStartMark = `${TRACE_START_MARK_PREFIX}-${this.randomId}-${this.name}`;\n this.traceStopMark = `${TRACE_STOP_MARK_PREFIX}-${this.randomId}-${this.name}`;\n this.traceMeasure =\n traceMeasureName ||\n `${TRACE_MEASURE_PREFIX}-${this.randomId}-${this.name}`;\n\n if (traceMeasureName) {\n // For the case of direct user timing traces, no start stop will happen. The measure object\n // is already available.\n this.calculateTraceMetrics();\n }\n }\n }\n\n /**\n * Starts a trace. The measurement of the duration starts at this point.\n */\n start(): void {\n if (this.state !== TraceState.UNINITIALIZED) {\n throw ERROR_FACTORY.create(ErrorCode.TRACE_STARTED_BEFORE, {\n traceName: this.name\n });\n }\n this.api.mark(this.traceStartMark);\n this.state = TraceState.RUNNING;\n }\n\n /**\n * Stops the trace. The measurement of the duration of the trace stops at this point and trace\n * is logged.\n */\n stop(): void {\n if (this.state !== TraceState.RUNNING) {\n throw ERROR_FACTORY.create(ErrorCode.TRACE_STOPPED_BEFORE, {\n traceName: this.name\n });\n }\n this.state = TraceState.TERMINATED;\n this.api.mark(this.traceStopMark);\n this.api.measure(\n this.traceMeasure,\n this.traceStartMark,\n this.traceStopMark\n );\n this.calculateTraceMetrics();\n logTrace(this);\n }\n\n /**\n * Records a trace with predetermined values. If this method is used a trace is created and logged\n * directly. No need to use start and stop methods.\n * @param startTime Trace start time since epoch in millisec\n * @param duration The duraction of the trace in millisec\n * @param options An object which can optionally hold maps of custom metrics and custom attributes\n */\n record(\n startTime: number,\n duration: number,\n options?: {\n metrics?: { [key: string]: number };\n attributes?: { [key: string]: string };\n }\n ): void {\n if (startTime <= 0) {\n throw ERROR_FACTORY.create(ErrorCode.NONPOSITIVE_TRACE_START_TIME, {\n traceName: this.name\n });\n }\n if (duration <= 0) {\n throw ERROR_FACTORY.create(ErrorCode.NONPOSITIVE_TRACE_DURATION, {\n traceName: this.name\n });\n }\n\n this.durationUs = Math.floor(duration * 1000);\n this.startTimeUs = Math.floor(startTime * 1000);\n if (options && options.attributes) {\n this.customAttributes = { ...options.attributes };\n }\n if (options && options.metrics) {\n for (const metricName of Object.keys(options.metrics)) {\n if (!isNaN(Number(options.metrics[metricName]))) {\n this.counters[metricName] = Math.floor(\n Number(options.metrics[metricName])\n );\n }\n }\n }\n logTrace(this);\n }\n\n /**\n * Increments a custom metric by a certain number or 1 if number not specified. Will create a new\n * custom metric if one with the given name does not exist. The value will be floored down to an\n * integer.\n * @param counter Name of the custom metric\n * @param numAsInteger Increment by value\n */\n incrementMetric(counter: string, numAsInteger = 1): void {\n if (this.counters[counter] === undefined) {\n this.putMetric(counter, numAsInteger);\n } else {\n this.putMetric(counter, this.counters[counter] + numAsInteger);\n }\n }\n\n /**\n * Sets a custom metric to a specified value. Will create a new custom metric if one with the\n * given name does not exist. The value will be floored down to an integer.\n * @param counter Name of the custom metric\n * @param numAsInteger Set custom metric to this value\n */\n putMetric(counter: string, numAsInteger: number): void {\n if (isValidMetricName(counter, this.name)) {\n this.counters[counter] = convertMetricValueToInteger(numAsInteger ?? 0);\n } else {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_CUSTOM_METRIC_NAME, {\n customMetricName: counter\n });\n }\n }\n\n /**\n * Returns the value of the custom metric by that name. If a custom metric with that name does\n * not exist will return zero.\n * @param counter\n */\n getMetric(counter: string): number {\n return this.counters[counter] || 0;\n }\n\n /**\n * Sets a custom attribute of a trace to a certain value.\n * @param attr\n * @param value\n */\n putAttribute(attr: string, value: string): void {\n const isValidName = isValidCustomAttributeName(attr);\n const isValidValue = isValidCustomAttributeValue(value);\n if (isValidName && isValidValue) {\n this.customAttributes[attr] = value;\n return;\n }\n // Throw appropriate error when the attribute name or value is invalid.\n if (!isValidName) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_ATTRIBUTE_NAME, {\n attributeName: attr\n });\n }\n if (!isValidValue) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_ATTRIBUTE_VALUE, {\n attributeValue: value\n });\n }\n }\n\n /**\n * Retrieves the value a custom attribute of a trace is set to.\n * @param attr\n */\n getAttribute(attr: string): string | undefined {\n return this.customAttributes[attr];\n }\n\n removeAttribute(attr: string): void {\n if (this.customAttributes[attr] === undefined) {\n return;\n }\n delete this.customAttributes[attr];\n }\n\n getAttributes(): { [key: string]: string } {\n return { ...this.customAttributes };\n }\n\n private setStartTime(startTime: number): void {\n this.startTimeUs = startTime;\n }\n\n private setDuration(duration: number): void {\n this.durationUs = duration;\n }\n\n /**\n * Calculates and assigns the duration and start time of the trace using the measure performance\n * entry.\n */\n private calculateTraceMetrics(): void {\n const perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);\n const perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];\n if (perfMeasureEntry) {\n this.durationUs = Math.floor(perfMeasureEntry.duration * 1000);\n this.startTimeUs = Math.floor(\n (perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000\n );\n }\n }\n\n /**\n * @param navigationTimings A single element array which contains the navigationTIming object of\n * the page load\n * @param paintTimings A array which contains paintTiming object of the page load\n * @param firstInputDelay First input delay in millisec\n */\n static createOobTrace(\n performanceController: PerformanceController,\n navigationTimings: PerformanceNavigationTiming[],\n paintTimings: PerformanceEntry[],\n firstInputDelay?: number\n ): void {\n const route = Api.getInstance().getUrl();\n if (!route) {\n return;\n }\n const trace = new Trace(\n performanceController,\n OOB_TRACE_PAGE_LOAD_PREFIX + route,\n true\n );\n const timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);\n trace.setStartTime(timeOriginUs);\n\n // navigationTimings includes only one element.\n if (navigationTimings && navigationTimings[0]) {\n trace.setDuration(Math.floor(navigationTimings[0].duration * 1000));\n trace.putMetric(\n 'domInteractive',\n Math.floor(navigationTimings[0].domInteractive * 1000)\n );\n trace.putMetric(\n 'domContentLoadedEventEnd',\n Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000)\n );\n trace.putMetric(\n 'loadEventEnd',\n Math.floor(navigationTimings[0].loadEventEnd * 1000)\n );\n }\n\n const FIRST_PAINT = 'first-paint';\n const FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';\n if (paintTimings) {\n const firstPaint = paintTimings.find(\n paintObject => paintObject.name === FIRST_PAINT\n );\n if (firstPaint && firstPaint.startTime) {\n trace.putMetric(\n FIRST_PAINT_COUNTER_NAME,\n Math.floor(firstPaint.startTime * 1000)\n );\n }\n const firstContentfulPaint = paintTimings.find(\n paintObject => paintObject.name === FIRST_CONTENTFUL_PAINT\n );\n if (firstContentfulPaint && firstContentfulPaint.startTime) {\n trace.putMetric(\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n Math.floor(firstContentfulPaint.startTime * 1000)\n );\n }\n\n if (firstInputDelay) {\n trace.putMetric(\n FIRST_INPUT_DELAY_COUNTER_NAME,\n Math.floor(firstInputDelay * 1000)\n );\n }\n }\n\n logTrace(trace);\n }\n\n static createUserTimingTrace(\n performanceController: PerformanceController,\n measureName: string\n ): void {\n const trace = new Trace(\n performanceController,\n measureName,\n false,\n measureName\n );\n logTrace(trace);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Api } from '../services/api_service';\nimport { logNetworkRequest } from '../services/perf_logger';\nimport { PerformanceController } from '../controllers/perf';\n\n// The order of values of this enum should not be changed.\nexport const enum HttpMethod {\n HTTP_METHOD_UNKNOWN = 0,\n GET = 1,\n PUT = 2,\n POST = 3,\n DELETE = 4,\n HEAD = 5,\n PATCH = 6,\n OPTIONS = 7,\n TRACE = 8,\n CONNECT = 9\n}\n\n// Durations are in microseconds.\nexport interface NetworkRequest {\n performanceController: PerformanceController;\n url: string;\n httpMethod?: HttpMethod;\n requestPayloadBytes?: number;\n responsePayloadBytes?: number;\n httpResponseCode?: number;\n responseContentType?: string;\n startTimeUs?: number;\n timeToRequestCompletedUs?: number;\n timeToResponseInitiatedUs?: number;\n timeToResponseCompletedUs?: number;\n}\n\nexport function createNetworkRequestEntry(\n performanceController: PerformanceController,\n entry: PerformanceEntry\n): void {\n const performanceEntry = entry as PerformanceResourceTiming;\n if (!performanceEntry || performanceEntry.responseStart === undefined) {\n return;\n }\n const timeOrigin = Api.getInstance().getTimeOrigin();\n const startTimeUs = Math.floor(\n (performanceEntry.startTime + timeOrigin) * 1000\n );\n const timeToResponseInitiatedUs = performanceEntry.responseStart\n ? Math.floor(\n (performanceEntry.responseStart - performanceEntry.startTime) * 1000\n )\n : undefined;\n const timeToResponseCompletedUs = Math.floor(\n (performanceEntry.responseEnd - performanceEntry.startTime) * 1000\n );\n // Remove the query params from logged network request url.\n const url = performanceEntry.name && performanceEntry.name.split('?')[0];\n const networkRequest: NetworkRequest = {\n performanceController,\n url,\n responsePayloadBytes: performanceEntry.transferSize,\n startTimeUs,\n timeToResponseInitiatedUs,\n timeToResponseCompletedUs\n };\n\n logNetworkRequest(networkRequest);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Api } from './api_service';\nimport { Trace } from '../resources/trace';\nimport { createNetworkRequestEntry } from '../resources/network_request';\nimport { TRACE_MEASURE_PREFIX } from '../constants';\nimport { getIid } from './iid_service';\nimport { PerformanceController } from '../controllers/perf';\n\nconst FID_WAIT_TIME_MS = 5000;\n\nexport function setupOobResources(\n performanceController: PerformanceController\n): void {\n // Do not initialize unless iid is available.\n if (!getIid()) {\n return;\n }\n // The load event might not have fired yet, and that means performance navigation timing\n // object has a duration of 0. The setup should run after all current tasks in js queue.\n setTimeout(() => setupOobTraces(performanceController), 0);\n setTimeout(() => setupNetworkRequests(performanceController), 0);\n setTimeout(() => setupUserTimingTraces(performanceController), 0);\n}\n\nfunction setupNetworkRequests(\n performanceController: PerformanceController\n): void {\n const api = Api.getInstance();\n const resources = api.getEntriesByType('resource');\n for (const resource of resources) {\n createNetworkRequestEntry(performanceController, resource);\n }\n api.setupObserver('resource', entry =>\n createNetworkRequestEntry(performanceController, entry)\n );\n}\n\nfunction setupOobTraces(performanceController: PerformanceController): void {\n const api = Api.getInstance();\n const navigationTimings = api.getEntriesByType(\n 'navigation'\n ) as PerformanceNavigationTiming[];\n const paintTimings = api.getEntriesByType('paint');\n // If First Input Desly polyfill is added to the page, report the fid value.\n // https://github.com/GoogleChromeLabs/first-input-delay\n if (api.onFirstInputDelay) {\n // If the fid call back is not called for certain time, continue without it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let timeoutId: any = setTimeout(() => {\n Trace.createOobTrace(\n performanceController,\n navigationTimings,\n paintTimings\n );\n timeoutId = undefined;\n }, FID_WAIT_TIME_MS);\n api.onFirstInputDelay((fid: number) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n Trace.createOobTrace(\n performanceController,\n navigationTimings,\n paintTimings,\n fid\n );\n }\n });\n } else {\n Trace.createOobTrace(\n performanceController,\n navigationTimings,\n paintTimings\n );\n }\n}\n\nfunction setupUserTimingTraces(\n performanceController: PerformanceController\n): void {\n const api = Api.getInstance();\n // Run through the measure performance entries collected up to this point.\n const measures = api.getEntriesByType('measure');\n for (const measure of measures) {\n createUserTimingTrace(performanceController, measure);\n }\n // Setup an observer to capture the measures from this point on.\n api.setupObserver('measure', entry =>\n createUserTimingTrace(performanceController, entry)\n );\n}\n\nfunction createUserTimingTrace(\n performanceController: PerformanceController,\n measure: PerformanceEntry\n): void {\n const measureName = measure.name;\n // Do not create a trace, if the user timing marks and measures are created by the sdk itself.\n if (\n measureName.substring(0, TRACE_MEASURE_PREFIX.length) ===\n TRACE_MEASURE_PREFIX\n ) {\n return;\n }\n Trace.createUserTimingTrace(performanceController, measureName);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { setupOobResources } from '../services/oob_resources_service';\nimport { SettingsService } from '../services/settings_service';\nimport { getInitializationPromise } from '../services/initialization_service';\nimport { Api } from '../services/api_service';\nimport { FirebaseApp } from '@firebase/app';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { PerformanceSettings, FirebasePerformance } from '../public_types';\nimport { validateIndexedDBOpenable } from '@firebase/util';\nimport { setupTransportService } from '../services/transport_service';\nimport { consoleLogger } from '../utils/console_logger';\n\nexport class PerformanceController implements FirebasePerformance {\n private initialized: boolean = false;\n\n constructor(\n readonly app: FirebaseApp,\n readonly installations: _FirebaseInstallationsInternal\n ) {}\n\n /**\n * This method *must* be called internally as part of creating a\n * PerformanceController instance.\n *\n * Currently it's not possible to pass the settings object through the\n * constructor using Components, so this method exists to be called with the\n * desired settings, to ensure nothing is collected without the user's\n * consent.\n */\n _init(settings?: PerformanceSettings): void {\n if (this.initialized) {\n return;\n }\n\n if (settings?.dataCollectionEnabled !== undefined) {\n this.dataCollectionEnabled = settings.dataCollectionEnabled;\n }\n if (settings?.instrumentationEnabled !== undefined) {\n this.instrumentationEnabled = settings.instrumentationEnabled;\n }\n\n if (Api.getInstance().requiredApisAvailable()) {\n validateIndexedDBOpenable()\n .then(isAvailable => {\n if (isAvailable) {\n setupTransportService();\n getInitializationPromise(this).then(\n () => setupOobResources(this),\n () => setupOobResources(this)\n );\n this.initialized = true;\n }\n })\n .catch(error => {\n consoleLogger.info(`Environment doesn't support IndexedDB: ${error}`);\n });\n } else {\n consoleLogger.info(\n 'Firebase Performance cannot start if the browser does not support ' +\n '\"Fetch\" and \"Promise\", or cookies are disabled.'\n );\n }\n }\n\n set instrumentationEnabled(val: boolean) {\n SettingsService.getInstance().instrumentationEnabled = val;\n }\n get instrumentationEnabled(): boolean {\n return SettingsService.getInstance().instrumentationEnabled;\n }\n\n set dataCollectionEnabled(val: boolean) {\n SettingsService.getInstance().dataCollectionEnabled = val;\n }\n get dataCollectionEnabled(): boolean {\n return SettingsService.getInstance().dataCollectionEnabled;\n }\n}\n","/**\n * Firebase Performance Monitoring\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebasePerformance,\n PerformanceSettings,\n PerformanceTrace\n} from './public_types';\nimport { ERROR_FACTORY, ErrorCode } from './utils/errors';\nimport { setupApi } from './services/api_service';\nimport { PerformanceController } from './controllers/perf';\nimport {\n _registerComponent,\n _getProvider,\n registerVersion,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n InstanceFactory,\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { name, version } from '../package.json';\nimport { Trace } from './resources/trace';\nimport '@firebase/installations';\nimport { deepEqual, getModularInstance } from '@firebase/util';\n\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\n * Returns a {@link FirebasePerformance} instance for the given app.\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n * @public\n */\nexport function getPerformance(\n app: FirebaseApp = getApp()\n): FirebasePerformance {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'performance');\n const perfInstance = provider.getImmediate() as PerformanceController;\n return perfInstance;\n}\n\n/**\n * Returns a {@link FirebasePerformance} instance for the given app. Can only be called once.\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n * @param settings - Optional settings for the {@link FirebasePerformance} instance.\n * @public\n */\nexport function initializePerformance(\n app: FirebaseApp,\n settings?: PerformanceSettings\n): FirebasePerformance {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'performance');\n\n // throw if an instance was already created.\n // It could happen if initializePerformance() is called more than once, or getPerformance() is called first.\n if (provider.isInitialized()) {\n const existingInstance = provider.getImmediate();\n const initialSettings = provider.getOptions() as PerformanceSettings;\n if (deepEqual(initialSettings, settings ?? {})) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(ErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const perfInstance = provider.initialize({\n options: settings\n }) as PerformanceController;\n return perfInstance;\n}\n\n/**\n * Returns a new `PerformanceTrace` instance.\n * @param performance - The {@link FirebasePerformance} instance to use.\n * @param name - The name of the trace.\n * @public\n */\nexport function trace(\n performance: FirebasePerformance,\n name: string\n): PerformanceTrace {\n performance = getModularInstance(performance);\n return new Trace(performance as PerformanceController, name);\n}\n\nconst factory: InstanceFactory<'performance'> = (\n container: ComponentContainer,\n { options: settings }: { options?: PerformanceSettings }\n) => {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\n if (app.name !== DEFAULT_ENTRY_NAME) {\n throw ERROR_FACTORY.create(ErrorCode.FB_NOT_DEFAULT);\n }\n if (typeof window === 'undefined') {\n throw ERROR_FACTORY.create(ErrorCode.NO_WINDOW);\n }\n setupApi(window);\n const perfInstance = new PerformanceController(app, installations);\n perfInstance._init(settings);\n\n return perfInstance;\n};\n\nfunction registerPerformance(): void {\n _registerComponent(\n new Component('performance', factory, ComponentType.PUBLIC)\n );\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterPerformance();\n\nexport { FirebasePerformance, PerformanceSettings, PerformanceTrace };\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n trace,\n FirebasePerformance,\n // The PerformanceTrace type has not changed between modular and non-modular packages.\n PerformanceTrace\n} from '@firebase/performance';\nimport { FirebasePerformance as FirebasePerformanceCompat } from '@firebase/performance-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\n\nexport class PerformanceCompatImpl\n implements FirebasePerformanceCompat, _FirebaseService\n{\n constructor(\n public app: FirebaseApp,\n readonly _delegate: FirebasePerformance\n ) {}\n\n get instrumentationEnabled(): boolean {\n return this._delegate.instrumentationEnabled;\n }\n\n set instrumentationEnabled(val: boolean) {\n this._delegate.instrumentationEnabled = val;\n }\n\n get dataCollectionEnabled(): boolean {\n return this._delegate.dataCollectionEnabled;\n }\n\n set dataCollectionEnabled(val: boolean) {\n this._delegate.dataCollectionEnabled = val;\n }\n\n trace(traceName: string): PerformanceTrace {\n return trace(this._delegate, traceName);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the\n * Remote Config server (https://firebase.google.com/docs/reference/remote-config/rest).\n *\n * <p>Abstracts throttle, response cache and network implementation details.\n *\n * <p>Modeled after the native {@link GlobalFetch} interface, which is relatively modern and\n * convenient, but simplified for Remote Config's use case.\n *\n * Disambiguation: {@link GlobalFetch} interface and the Remote Config service define \"fetch\"\n * methods. The RestClient uses the former to make HTTP calls. This interface abstracts the latter.\n */\nexport interface RemoteConfigFetchClient {\n /**\n * @throws if response status is not 200 or 304.\n */\n fetch(request: FetchRequest): Promise<FetchResponse>;\n}\n\n/**\n * Defines a self-descriptive reference for config key-value pairs.\n */\nexport interface FirebaseRemoteConfigObject {\n [key: string]: string;\n}\n\n/**\n * Shims a minimal AbortSignal.\n *\n * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\n * swapped out if/when we do.\n */\nexport class RemoteConfigAbortSignal {\n listeners: Array<() => void> = [];\n addEventListener(listener: () => void): void {\n this.listeners.push(listener);\n }\n abort(): void {\n this.listeners.forEach(listener => listener());\n }\n}\n\n/**\n * Defines per-request inputs for the Remote Config fetch request.\n *\n * <p>Modeled after the native {@link Request} interface, but simplified for Remote Config's\n * use case.\n */\nexport interface FetchRequest {\n /**\n * Uses cached config if it is younger than this age.\n *\n * <p>Required because it's defined by settings, which always have a value.\n *\n * <p>Comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the native\n * Fetch API.\n */\n cacheMaxAgeMillis: number;\n\n /**\n * An event bus for the signal to abort a request.\n *\n * <p>Required because all requests should be abortable.\n *\n * <p>Comparable to the native\n * Fetch API's \"signal\" field on its request configuration object\n * https://fetch.spec.whatwg.org/#dom-requestinit-signal.\n *\n * <p>Disambiguation: Remote Config commonly refers to API inputs as\n * \"signals\". See the private ConfigFetchRequestBody interface for those:\n * http://google3/firebase/remote_config/web/src/core/rest_client.ts?l=14&rcl=255515243.\n */\n signal: RemoteConfigAbortSignal;\n\n /**\n * The ETag header value from the last response.\n *\n * <p>Optional in case this is the first request.\n *\n * <p>Comparable to passing `headers = { 'If-None-Match': <eTag> }` to the native Fetch API.\n */\n eTag?: string;\n}\n\n/**\n * Defines a successful response (200 or 304).\n *\n * <p>Modeled after the native {@link Response} interface, but simplified for Remote Config's\n * use case.\n */\nexport interface FetchResponse {\n /**\n * The HTTP status, which is useful for differentiating success responses with data from\n * those without.\n *\n * <p>{@link RemoteConfigClient} is modeled after the native {@link GlobalFetch} interface, so\n * HTTP status is first-class.\n *\n * <p>Disambiguation: the fetch response returns a legacy \"state\" value that is redundant with the\n * HTTP status code. The former is normalized into the latter.\n */\n status: number;\n\n /**\n * Defines the ETag response header value.\n *\n * <p>Only defined for 200 and 304 responses.\n */\n eTag?: string;\n\n /**\n * Defines the map of parameters returned as \"entries\" in the fetch response body.\n *\n * <p>Only defined for 200 responses.\n */\n config?: FirebaseRemoteConfigObject;\n\n // Note: we're not extracting experiment metadata until\n // ABT and Analytics have Web SDKs.\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const RC_COMPONENT_NAME = 'remote-config';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\n\nexport const enum ErrorCode {\n REGISTRATION_WINDOW = 'registration-window',\n REGISTRATION_PROJECT_ID = 'registration-project-id',\n REGISTRATION_API_KEY = 'registration-api-key',\n REGISTRATION_APP_ID = 'registration-app-id',\n STORAGE_OPEN = 'storage-open',\n STORAGE_GET = 'storage-get',\n STORAGE_SET = 'storage-set',\n STORAGE_DELETE = 'storage-delete',\n FETCH_NETWORK = 'fetch-client-network',\n FETCH_TIMEOUT = 'fetch-timeout',\n FETCH_THROTTLE = 'fetch-throttle',\n FETCH_PARSE = 'fetch-client-parse',\n FETCH_STATUS = 'fetch-status',\n INDEXED_DB_UNAVAILABLE = 'indexed-db-unavailable'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.REGISTRATION_WINDOW]:\n 'Undefined window object. This SDK only supports usage in a browser environment.',\n [ErrorCode.REGISTRATION_PROJECT_ID]:\n 'Undefined project identifier. Check Firebase app initialization.',\n [ErrorCode.REGISTRATION_API_KEY]:\n 'Undefined API key. Check Firebase app initialization.',\n [ErrorCode.REGISTRATION_APP_ID]:\n 'Undefined app identifier. Check Firebase app initialization.',\n [ErrorCode.STORAGE_OPEN]:\n 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.STORAGE_GET]:\n 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.STORAGE_SET]:\n 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.STORAGE_DELETE]:\n 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.FETCH_NETWORK]:\n 'Fetch client failed to connect to a network. Check Internet connection.' +\n ' Original error: {$originalErrorMessage}.',\n [ErrorCode.FETCH_TIMEOUT]:\n 'The config fetch request timed out. ' +\n ' Configure timeout using \"fetchTimeoutMillis\" SDK setting.',\n [ErrorCode.FETCH_THROTTLE]:\n 'The config fetch request timed out while in an exponential backoff state.' +\n ' Configure timeout using \"fetchTimeoutMillis\" SDK setting.' +\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n [ErrorCode.FETCH_PARSE]:\n 'Fetch client could not parse response.' +\n ' Original error: {$originalErrorMessage}.',\n [ErrorCode.FETCH_STATUS]:\n 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n [ErrorCode.INDEXED_DB_UNAVAILABLE]:\n 'Indexed DB is not supported by current browser'\n};\n\n// Note this is effectively a type system binding a code to params. This approach overlaps with the\n// role of TS interfaces, but works well for a few reasons:\n// 1) JS is unaware of TS interfaces, eg we can't test for interface implementation in JS\n// 2) callers should have access to a human-readable summary of the error and this interpolates\n// params into an error message;\n// 3) callers should be able to programmatically access data associated with an error, which\n// ErrorData provides.\ninterface ErrorParams {\n [ErrorCode.STORAGE_OPEN]: { originalErrorMessage: string | undefined };\n [ErrorCode.STORAGE_GET]: { originalErrorMessage: string | undefined };\n [ErrorCode.STORAGE_SET]: { originalErrorMessage: string | undefined };\n [ErrorCode.STORAGE_DELETE]: { originalErrorMessage: string | undefined };\n [ErrorCode.FETCH_NETWORK]: { originalErrorMessage: string };\n [ErrorCode.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n [ErrorCode.FETCH_PARSE]: { originalErrorMessage: string };\n [ErrorCode.FETCH_STATUS]: { httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n 'remoteconfig' /* service */,\n 'Remote Config' /* service name */,\n ERROR_DESCRIPTION_MAP\n);\n\n// Note how this is like typeof/instanceof, but for ErrorCode.\nexport function hasErrorCode(e: Error, errorCode: ErrorCode): boolean {\n return e instanceof FirebaseError && e.code.indexOf(errorCode) !== -1;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ValueType, ValueSource } from '@firebase/remote-config-types';\n\nconst DEFAULT_VALUE_FOR_BOOLEAN = false;\nconst DEFAULT_VALUE_FOR_STRING = '';\nconst DEFAULT_VALUE_FOR_NUMBER = 0;\n\nconst BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];\n\nexport class Value implements ValueType {\n constructor(\n private readonly _source: ValueSource,\n private readonly _value: string = DEFAULT_VALUE_FOR_STRING\n ) {}\n\n asString(): string {\n return this._value;\n }\n\n asBoolean(): boolean {\n if (this._source === 'static') {\n return DEFAULT_VALUE_FOR_BOOLEAN;\n }\n return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;\n }\n\n asNumber(): number {\n if (this._source === 'static') {\n return DEFAULT_VALUE_FOR_NUMBER;\n }\n let num = Number(this._value);\n if (isNaN(num)) {\n num = DEFAULT_VALUE_FOR_NUMBER;\n }\n return num;\n }\n\n getSource(): ValueSource {\n return this._source;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport {\n LogLevel as RemoteConfigLogLevel,\n RemoteConfig,\n Value\n} from './public_types';\nimport { RemoteConfigAbortSignal } from './client/remote_config_fetch_client';\nimport { RC_COMPONENT_NAME } from './constants';\nimport { ErrorCode, hasErrorCode } from './errors';\nimport { RemoteConfig as RemoteConfigImpl } from './remote_config';\nimport { Value as ValueImpl } from './value';\nimport { LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\n * @returns A {@link RemoteConfig} instance.\n *\n * @public\n */\nexport function getRemoteConfig(app: FirebaseApp = getApp()): RemoteConfig {\n app = getModularInstance(app);\n const rcProvider = _getProvider(app, RC_COMPONENT_NAME);\n return rcProvider.getImmediate();\n}\n\n/**\n * Makes the last fetched config available to the getters.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @returns A `Promise` which resolves to true if the current call activated the fetched configs.\n * If the fetched configs were already activated, the `Promise` will resolve to false.\n *\n * @public\n */\nexport async function activate(remoteConfig: RemoteConfig): Promise<boolean> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([\n rc._storage.getLastSuccessfulFetchResponse(),\n rc._storage.getActiveConfigEtag()\n ]);\n if (\n !lastSuccessfulFetchResponse ||\n !lastSuccessfulFetchResponse.config ||\n !lastSuccessfulFetchResponse.eTag ||\n lastSuccessfulFetchResponse.eTag === activeConfigEtag\n ) {\n // Either there is no successful fetched config, or is the same as current active\n // config.\n return false;\n }\n await Promise.all([\n rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),\n rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)\n ]);\n return true;\n}\n\n/**\n * Ensures the last activated config are available to the getters.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n *\n * @returns A `Promise` that resolves when the last activated config is available to the getters.\n * @public\n */\nexport function ensureInitialized(remoteConfig: RemoteConfig): Promise<void> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n if (!rc._initializePromise) {\n rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {\n rc._isInitializationComplete = true;\n });\n }\n return rc._initializePromise;\n}\n\n/**\n * Fetches and caches configuration from the Remote Config service.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @public\n */\nexport async function fetchConfig(remoteConfig: RemoteConfig): Promise<void> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n // Aborts the request after the given timeout, causing the fetch call to\n // reject with an `AbortError`.\n //\n // <p>Aborting after the request completes is a no-op, so we don't need a\n // corresponding `clearTimeout`.\n //\n // Locating abort logic here because:\n // * it uses a developer setting (timeout)\n // * it applies to all retries (like curl's max-time arg)\n // * it is consistent with the Fetch API's signal input\n const abortSignal = new RemoteConfigAbortSignal();\n\n setTimeout(async () => {\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n abortSignal.abort();\n }, rc.settings.fetchTimeoutMillis);\n\n // Catches *all* errors thrown by client so status can be set consistently.\n try {\n await rc._client.fetch({\n cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,\n signal: abortSignal\n });\n\n await rc._storageCache.setLastFetchStatus('success');\n } catch (e) {\n const lastFetchStatus = hasErrorCode(e as Error, ErrorCode.FETCH_THROTTLE)\n ? 'throttle'\n : 'failure';\n await rc._storageCache.setLastFetchStatus(lastFetchStatus);\n throw e;\n }\n}\n\n/**\n * Gets all config.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @returns All config.\n *\n * @public\n */\nexport function getAll(remoteConfig: RemoteConfig): Record<string, Value> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n return getAllKeys(\n rc._storageCache.getActiveConfig(),\n rc.defaultConfig\n ).reduce((allConfigs, key) => {\n allConfigs[key] = getValue(remoteConfig, key);\n return allConfigs;\n }, {} as Record<string, Value>);\n}\n\n/**\n * Gets the value for the given key as a boolean.\n *\n * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a boolean.\n * @public\n */\nexport function getBoolean(remoteConfig: RemoteConfig, key: string): boolean {\n return getValue(getModularInstance(remoteConfig), key).asBoolean();\n}\n\n/**\n * Gets the value for the given key as a number.\n *\n * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a number.\n *\n * @public\n */\nexport function getNumber(remoteConfig: RemoteConfig, key: string): number {\n return getValue(getModularInstance(remoteConfig), key).asNumber();\n}\n\n/**\n * Gets the value for the given key as a string.\n * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a string.\n *\n * @public\n */\nexport function getString(remoteConfig: RemoteConfig, key: string): string {\n return getValue(getModularInstance(remoteConfig), key).asString();\n}\n\n/**\n * Gets the {@link Value} for the given key.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key.\n *\n * @public\n */\nexport function getValue(remoteConfig: RemoteConfig, key: string): Value {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n if (!rc._isInitializationComplete) {\n rc._logger.debug(\n `A value was requested for key \"${key}\" before SDK initialization completed.` +\n ' Await on ensureInitialized if the intent was to get a previously activated value.'\n );\n }\n const activeConfig = rc._storageCache.getActiveConfig();\n if (activeConfig && activeConfig[key] !== undefined) {\n return new ValueImpl('remote', activeConfig[key]);\n } else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {\n return new ValueImpl('default', String(rc.defaultConfig[key]));\n }\n rc._logger.debug(\n `Returning static value for key \"${key}\".` +\n ' Define a default or remote value if this is unintentional.'\n );\n return new ValueImpl('static');\n}\n\n/**\n * Defines the log level to use.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param logLevel - The log level to set.\n *\n * @public\n */\nexport function setLogLevel(\n remoteConfig: RemoteConfig,\n logLevel: RemoteConfigLogLevel\n): void {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n switch (logLevel) {\n case 'debug':\n rc._logger.logLevel = FirebaseLogLevel.DEBUG;\n break;\n case 'silent':\n rc._logger.logLevel = FirebaseLogLevel.SILENT;\n break;\n default:\n rc._logger.logLevel = FirebaseLogLevel.ERROR;\n }\n}\n\n/**\n * Dedupes and returns an array of all the keys of the received objects.\n */\nfunction getAllKeys(obj1: {} = {}, obj2: {} = {}): string[] {\n return Object.keys({ ...obj1, ...obj2 });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StorageCache } from '../storage/storage_cache';\nimport {\n FetchResponse,\n RemoteConfigFetchClient,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { Storage } from '../storage/storage';\nimport { Logger } from '@firebase/logger';\n\n/**\n * Implements the {@link RemoteConfigClient} abstraction with success response caching.\n *\n * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service\n * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the\n * Cache API doesn't support matching entries by time.\n */\nexport class CachingClient implements RemoteConfigFetchClient {\n constructor(\n private readonly client: RemoteConfigFetchClient,\n private readonly storage: Storage,\n private readonly storageCache: StorageCache,\n private readonly logger: Logger\n ) {}\n\n /**\n * Returns true if the age of the cached fetched configs is less than or equal to\n * {@link Settings#minimumFetchIntervalInSeconds}.\n *\n * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the\n * native Fetch API.\n *\n * <p>Visible for testing.\n */\n isCachedDataFresh(\n cacheMaxAgeMillis: number,\n lastSuccessfulFetchTimestampMillis: number | undefined\n ): boolean {\n // Cache can only be fresh if it's populated.\n if (!lastSuccessfulFetchTimestampMillis) {\n this.logger.debug('Config fetch cache check. Cache unpopulated.');\n return false;\n }\n\n // Calculates age of cache entry.\n const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;\n\n const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;\n\n this.logger.debug(\n 'Config fetch cache check.' +\n ` Cache age millis: ${cacheAgeMillis}.` +\n ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +\n ` Is cache hit: ${isCachedDataFresh}.`\n );\n\n return isCachedDataFresh;\n }\n\n async fetch(request: FetchRequest): Promise<FetchResponse> {\n // Reads from persisted storage to avoid cache miss if callers don't wait on initialization.\n const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] =\n await Promise.all([\n this.storage.getLastSuccessfulFetchTimestampMillis(),\n this.storage.getLastSuccessfulFetchResponse()\n ]);\n\n // Exits early on cache hit.\n if (\n lastSuccessfulFetchResponse &&\n this.isCachedDataFresh(\n request.cacheMaxAgeMillis,\n lastSuccessfulFetchTimestampMillis\n )\n ) {\n return lastSuccessfulFetchResponse;\n }\n\n // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API\n // that allows the caller to pass an ETag.\n request.eTag =\n lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;\n\n // Falls back to service on cache miss.\n const response = await this.client.fetch(request);\n\n // Fetch throws for non-success responses, so success is guaranteed here.\n\n const storageOperations = [\n // Uses write-through cache for consistency with synchronous public API.\n this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())\n ];\n\n if (response.status === 200) {\n // Caches response only if it has changed, ie non-304 responses.\n storageOperations.push(\n this.storage.setLastSuccessfulFetchResponse(response)\n );\n }\n\n await Promise.all(storageOperations);\n\n return response;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchResponse,\n RemoteConfigFetchClient,\n FirebaseRemoteConfigObject,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { getUserLanguage } from '../language';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\n\n/**\n * Defines request body parameters required to call the fetch API:\n * https://firebase.google.com/docs/reference/remote-config/rest\n *\n * <p>Not exported because this file encapsulates REST API specifics.\n *\n * <p>Not passing User Properties because Analytics' source of truth on Web is server-side.\n */\ninterface FetchRequestBody {\n // Disables camelcase linting for request body params.\n /* eslint-disable camelcase*/\n sdk_version: string;\n app_instance_id: string;\n app_instance_id_token: string;\n app_id: string;\n language_code: string;\n /* eslint-enable camelcase */\n}\n\n/**\n * Implements the Client abstraction for the Remote Config REST API.\n */\nexport class RestClient implements RemoteConfigFetchClient {\n constructor(\n private readonly firebaseInstallations: _FirebaseInstallationsInternal,\n private readonly sdkVersion: string,\n private readonly namespace: string,\n private readonly projectId: string,\n private readonly apiKey: string,\n private readonly appId: string\n ) {}\n\n /**\n * Fetches from the Remote Config REST API.\n *\n * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't\n * connect to the network.\n * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the\n * fetch response.\n * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status.\n */\n async fetch(request: FetchRequest): Promise<FetchResponse> {\n const [installationId, installationToken] = await Promise.all([\n this.firebaseInstallations.getId(),\n this.firebaseInstallations.getToken()\n ]);\n\n const urlBase =\n window.FIREBASE_REMOTE_CONFIG_URL_BASE ||\n 'https://firebaseremoteconfig.googleapis.com';\n\n const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;\n\n const headers = {\n 'Content-Type': 'application/json',\n 'Content-Encoding': 'gzip',\n // Deviates from pure decorator by not passing max-age header since we don't currently have\n // service behavior using that header.\n 'If-None-Match': request.eTag || '*'\n };\n\n const requestBody: FetchRequestBody = {\n /* eslint-disable camelcase */\n sdk_version: this.sdkVersion,\n app_instance_id: installationId,\n app_instance_id_token: installationToken,\n app_id: this.appId,\n language_code: getUserLanguage()\n /* eslint-enable camelcase */\n };\n\n const options = {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody)\n };\n\n // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator.\n const fetchPromise = fetch(url, options);\n const timeoutPromise = new Promise((_resolve, reject) => {\n // Maps async event listener to Promise API.\n request.signal.addEventListener(() => {\n // Emulates https://heycam.github.io/webidl/#aborterror\n const error = new Error('The operation was aborted.');\n error.name = 'AbortError';\n reject(error);\n });\n });\n\n let response;\n try {\n await Promise.race([fetchPromise, timeoutPromise]);\n response = await fetchPromise;\n } catch (originalError) {\n let errorCode = ErrorCode.FETCH_NETWORK;\n if ((originalError as Error)?.name === 'AbortError') {\n errorCode = ErrorCode.FETCH_TIMEOUT;\n }\n throw ERROR_FACTORY.create(errorCode, {\n originalErrorMessage: (originalError as Error)?.message\n });\n }\n\n let status = response.status;\n\n // Normalizes nullable header to optional.\n const responseEtag = response.headers.get('ETag') || undefined;\n\n let config: FirebaseRemoteConfigObject | undefined;\n let state: string | undefined;\n\n // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n // Requesting application/json and checking for a 200 ensures there's JSON data.\n if (response.status === 200) {\n let responseBody;\n try {\n responseBody = await response.json();\n } catch (originalError) {\n throw ERROR_FACTORY.create(ErrorCode.FETCH_PARSE, {\n originalErrorMessage: (originalError as Error)?.message\n });\n }\n config = responseBody['entries'];\n state = responseBody['state'];\n }\n\n // Normalizes based on legacy state.\n if (state === 'INSTANCE_STATE_UNSPECIFIED') {\n status = 500;\n } else if (state === 'NO_CHANGE') {\n status = 304;\n } else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {\n // These cases can be fixed remotely, so normalize to safe value.\n config = {};\n }\n\n // Normalize to exception-based control flow for non-success cases.\n // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for\n // differentiating success states (200 from 304; the state body param is undefined in a\n // standard 304).\n if (status !== 304 && status !== 200) {\n throw ERROR_FACTORY.create(ErrorCode.FETCH_STATUS, {\n httpStatus: status\n });\n }\n\n return { status, eTag: responseEtag, config };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Attempts to get the most accurate browser language setting.\n *\n * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript.\n *\n * <p>Defers default language specification to server logic for consistency.\n *\n * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}.\n */\nexport function getUserLanguage(\n navigatorLanguage: NavigatorLanguage = navigator\n): string {\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language\n // Polyfill otherwise.\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RemoteConfigAbortSignal,\n RemoteConfigFetchClient,\n FetchResponse,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { ThrottleMetadata, Storage } from '../storage/storage';\nimport { ErrorCode, ERROR_FACTORY } from '../errors';\nimport { FirebaseError, calculateBackoffMillis } from '@firebase/util';\n\n/**\n * Supports waiting on a backoff by:\n *\n * <ul>\n * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>\n * <li>Listening on a signal bus for abort events, just like the Fetch API</li>\n * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled\n * request appear the same.</li>\n * </ul>\n *\n * <p>Visible for testing.\n */\nexport function setAbortableTimeout(\n signal: RemoteConfigAbortSignal,\n throttleEndTimeMillis: number\n): Promise<void> {\n return new Promise((resolve, reject) => {\n // Derives backoff from given end time, normalizing negative numbers to zero.\n const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\n\n const timeout = setTimeout(resolve, backoffMillis);\n\n // Adds listener, rather than sets onabort, because signal is a shared object.\n signal.addEventListener(() => {\n clearTimeout(timeout);\n\n // If the request completes before this timeout, the rejection has no effect.\n reject(\n ERROR_FACTORY.create(ErrorCode.FETCH_THROTTLE, {\n throttleEndTimeMillis\n })\n );\n });\n });\n}\n\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n if (!(e instanceof FirebaseError) || !e.customData) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e.customData['httpStatus']);\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\n/**\n * Decorates a Client with retry logic.\n *\n * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache\n * responses (because the SDK has no use for error responses).\n */\nexport class RetryingClient implements RemoteConfigFetchClient {\n constructor(\n private readonly client: RemoteConfigFetchClient,\n private readonly storage: Storage\n ) {}\n\n async fetch(request: FetchRequest): Promise<FetchResponse> {\n const throttleMetadata = (await this.storage.getThrottleMetadata()) || {\n backoffCount: 0,\n throttleEndTimeMillis: Date.now()\n };\n\n return this.attemptFetch(request, throttleMetadata);\n }\n\n /**\n * A recursive helper for attempting a fetch request repeatedly.\n *\n * @throws any non-retriable errors.\n */\n async attemptFetch(\n request: FetchRequest,\n { throttleEndTimeMillis, backoffCount }: ThrottleMetadata\n ): Promise<FetchResponse> {\n // Starts with a (potentially zero) timeout to support resumption from stored state.\n // Ensures the throttle end time is honored if the last attempt timed out.\n // Note the SDK will never make a request if the fetch timeout expires at this point.\n await setAbortableTimeout(request.signal, throttleEndTimeMillis);\n\n try {\n const response = await this.client.fetch(request);\n\n // Note the SDK only clears throttle state if response is success or non-retriable.\n await this.storage.deleteThrottleMetadata();\n\n return response;\n } catch (e) {\n if (!isRetriableError(e as Error)) {\n throw e;\n }\n\n // Increments backoff state.\n const throttleMetadata = {\n throttleEndTimeMillis:\n Date.now() + calculateBackoffMillis(backoffCount),\n backoffCount: backoffCount + 1\n };\n\n // Persists state.\n await this.storage.setThrottleMetadata(throttleMetadata);\n\n return this.attemptFetch(request, throttleMetadata);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n RemoteConfig as RemoteConfigType,\n FetchStatus,\n RemoteConfigSettings\n} from './public_types';\nimport { StorageCache } from './storage/storage_cache';\nimport { RemoteConfigFetchClient } from './client/remote_config_fetch_client';\nimport { Storage } from './storage/storage';\nimport { Logger } from '@firebase/logger';\n\nconst DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute\nconst DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours.\n\n/**\n * Encapsulates business logic mapping network and storage dependencies to the public SDK API.\n *\n * See {@link https://github.com/FirebasePrivate/firebase-js-sdk/blob/master/packages/firebase/index.d.ts|interface documentation} for method descriptions.\n */\nexport class RemoteConfig implements RemoteConfigType {\n /**\n * Tracks completion of initialization promise.\n * @internal\n */\n _isInitializationComplete = false;\n\n /**\n * De-duplicates initialization calls.\n * @internal\n */\n _initializePromise?: Promise<void>;\n\n settings: RemoteConfigSettings = {\n fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,\n minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS\n };\n\n defaultConfig: { [key: string]: string | number | boolean } = {};\n\n get fetchTimeMillis(): number {\n return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;\n }\n\n get lastFetchStatus(): FetchStatus {\n return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';\n }\n\n constructor(\n // Required by FirebaseServiceFactory interface.\n readonly app: FirebaseApp,\n // JS doesn't support private yet\n // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an\n // underscore prefix.\n /**\n * @internal\n */\n readonly _client: RemoteConfigFetchClient,\n /**\n * @internal\n */\n readonly _storageCache: StorageCache,\n /**\n * @internal\n */\n readonly _storage: Storage,\n /**\n * @internal\n */\n readonly _logger: Logger\n ) {}\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchStatus } from '@firebase/remote-config-types';\nimport {\n FetchResponse,\n FirebaseRemoteConfigObject\n} from '../client/remote_config_fetch_client';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}.\n */\nfunction toFirebaseError(event: Event, errorCode: ErrorCode): FirebaseError {\n const originalError = (event.target as IDBRequest).error || undefined;\n return ERROR_FACTORY.create(errorCode, {\n originalErrorMessage: originalError && (originalError as Error)?.message\n });\n}\n\n/**\n * A general-purpose store keyed by app + namespace + {@link\n * ProjectNamespaceKeyFieldValue}.\n *\n * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact\n * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys\n * for a set of key-value pairs. See {@link Storage#createCompositeKey}.\n *\n * <p>Visible for testing.\n */\nexport const APP_NAMESPACE_STORE = 'app_namespace_store';\n\nconst DB_NAME = 'firebase_remote_config';\nconst DB_VERSION = 1;\n\n/**\n * Encapsulates metadata concerning throttled fetch requests.\n */\nexport interface ThrottleMetadata {\n // The number of times fetch has backed off. Used for resuming backoff after a timeout.\n backoffCount: number;\n // The Unix timestamp in milliseconds when callers can retry a request.\n throttleEndTimeMillis: number;\n}\n\n/**\n * Provides type-safety for the \"key\" field used by {@link APP_NAMESPACE_STORE}.\n *\n * <p>This seems like a small price to avoid potentially subtle bugs caused by a typo.\n */\ntype ProjectNamespaceKeyFieldValue =\n | 'active_config'\n | 'active_config_etag'\n | 'last_fetch_status'\n | 'last_successful_fetch_timestamp_millis'\n | 'last_successful_fetch_response'\n | 'settings'\n | 'throttle_metadata';\n\n// Visible for testing.\nexport function openDatabase(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n try {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n request.onerror = event => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_OPEN));\n };\n request.onsuccess = event => {\n resolve((event.target as IDBOpenDBRequest).result);\n };\n request.onupgradeneeded = event => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (event.oldVersion) {\n case 0:\n db.createObjectStore(APP_NAMESPACE_STORE, {\n keyPath: 'compositeKey'\n });\n }\n };\n } catch (error) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_OPEN, {\n originalErrorMessage: (error as Error)?.message\n })\n );\n }\n });\n}\n\n/**\n * Abstracts data persistence.\n */\nexport class Storage {\n /**\n * @param appId enables storage segmentation by app (ID + name).\n * @param appName enables storage segmentation by app (ID + name).\n * @param namespace enables storage segmentation by namespace.\n */\n constructor(\n private readonly appId: string,\n private readonly appName: string,\n private readonly namespace: string,\n private readonly openDbPromise = openDatabase()\n ) {}\n\n getLastFetchStatus(): Promise<FetchStatus | undefined> {\n return this.get<FetchStatus>('last_fetch_status');\n }\n\n setLastFetchStatus(status: FetchStatus): Promise<void> {\n return this.set<FetchStatus>('last_fetch_status', status);\n }\n\n // This is comparable to a cache entry timestamp. If we need to expire other data, we could\n // consider adding timestamp to all storage records and an optional max age arg to getters.\n getLastSuccessfulFetchTimestampMillis(): Promise<number | undefined> {\n return this.get<number>('last_successful_fetch_timestamp_millis');\n }\n\n setLastSuccessfulFetchTimestampMillis(timestamp: number): Promise<void> {\n return this.set<number>(\n 'last_successful_fetch_timestamp_millis',\n timestamp\n );\n }\n\n getLastSuccessfulFetchResponse(): Promise<FetchResponse | undefined> {\n return this.get<FetchResponse>('last_successful_fetch_response');\n }\n\n setLastSuccessfulFetchResponse(response: FetchResponse): Promise<void> {\n return this.set<FetchResponse>('last_successful_fetch_response', response);\n }\n\n getActiveConfig(): Promise<FirebaseRemoteConfigObject | undefined> {\n return this.get<FirebaseRemoteConfigObject>('active_config');\n }\n\n setActiveConfig(config: FirebaseRemoteConfigObject): Promise<void> {\n return this.set<FirebaseRemoteConfigObject>('active_config', config);\n }\n\n getActiveConfigEtag(): Promise<string | undefined> {\n return this.get<string>('active_config_etag');\n }\n\n setActiveConfigEtag(etag: string): Promise<void> {\n return this.set<string>('active_config_etag', etag);\n }\n\n getThrottleMetadata(): Promise<ThrottleMetadata | undefined> {\n return this.get<ThrottleMetadata>('throttle_metadata');\n }\n\n setThrottleMetadata(metadata: ThrottleMetadata): Promise<void> {\n return this.set<ThrottleMetadata>('throttle_metadata', metadata);\n }\n\n deleteThrottleMetadata(): Promise<void> {\n return this.delete('throttle_metadata');\n }\n\n async get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined> {\n const db = await this.openDbPromise;\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');\n const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n const compositeKey = this.createCompositeKey(key);\n try {\n const request = objectStore.get(compositeKey);\n request.onerror = event => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_GET));\n };\n request.onsuccess = event => {\n const result = (event.target as IDBRequest).result;\n if (result) {\n resolve(result.value);\n } else {\n resolve(undefined);\n }\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_GET, {\n originalErrorMessage: (e as Error)?.message\n })\n );\n }\n });\n }\n\n async set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void> {\n const db = await this.openDbPromise;\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n const compositeKey = this.createCompositeKey(key);\n try {\n const request = objectStore.put({\n compositeKey,\n value\n });\n request.onerror = (event: Event) => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_SET));\n };\n request.onsuccess = () => {\n resolve();\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_SET, {\n originalErrorMessage: (e as Error)?.message\n })\n );\n }\n });\n }\n\n async delete(key: ProjectNamespaceKeyFieldValue): Promise<void> {\n const db = await this.openDbPromise;\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n const compositeKey = this.createCompositeKey(key);\n try {\n const request = objectStore.delete(compositeKey);\n request.onerror = (event: Event) => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_DELETE));\n };\n request.onsuccess = () => {\n resolve();\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_DELETE, {\n originalErrorMessage: (e as Error)?.message\n })\n );\n }\n });\n }\n\n // Facilitates composite key functionality (which is unsupported in IE).\n createCompositeKey(key: ProjectNamespaceKeyFieldValue): string {\n return [this.appId, this.appName, this.namespace, key].join();\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchStatus } from '@firebase/remote-config-types';\nimport { FirebaseRemoteConfigObject } from '../client/remote_config_fetch_client';\nimport { Storage } from './storage';\n\n/**\n * A memory cache layer over storage to support the SDK's synchronous read requirements.\n */\nexport class StorageCache {\n constructor(private readonly storage: Storage) {}\n\n /**\n * Memory caches.\n */\n private lastFetchStatus?: FetchStatus;\n private lastSuccessfulFetchTimestampMillis?: number;\n private activeConfig?: FirebaseRemoteConfigObject;\n\n /**\n * Memory-only getters\n */\n getLastFetchStatus(): FetchStatus | undefined {\n return this.lastFetchStatus;\n }\n\n getLastSuccessfulFetchTimestampMillis(): number | undefined {\n return this.lastSuccessfulFetchTimestampMillis;\n }\n\n getActiveConfig(): FirebaseRemoteConfigObject | undefined {\n return this.activeConfig;\n }\n\n /**\n * Read-ahead getter\n */\n async loadFromStorage(): Promise<void> {\n const lastFetchStatusPromise = this.storage.getLastFetchStatus();\n const lastSuccessfulFetchTimestampMillisPromise =\n this.storage.getLastSuccessfulFetchTimestampMillis();\n const activeConfigPromise = this.storage.getActiveConfig();\n\n // Note:\n // 1. we consistently check for undefined to avoid clobbering defined values\n // in memory\n // 2. we defer awaiting to improve readability, as opposed to destructuring\n // a Promise.all result, for example\n\n const lastFetchStatus = await lastFetchStatusPromise;\n if (lastFetchStatus) {\n this.lastFetchStatus = lastFetchStatus;\n }\n\n const lastSuccessfulFetchTimestampMillis =\n await lastSuccessfulFetchTimestampMillisPromise;\n if (lastSuccessfulFetchTimestampMillis) {\n this.lastSuccessfulFetchTimestampMillis =\n lastSuccessfulFetchTimestampMillis;\n }\n\n const activeConfig = await activeConfigPromise;\n if (activeConfig) {\n this.activeConfig = activeConfig;\n }\n }\n\n /**\n * Write-through setters\n */\n setLastFetchStatus(status: FetchStatus): Promise<void> {\n this.lastFetchStatus = status;\n return this.storage.setLastFetchStatus(status);\n }\n\n setLastSuccessfulFetchTimestampMillis(\n timestampMillis: number\n ): Promise<void> {\n this.lastSuccessfulFetchTimestampMillis = timestampMillis;\n return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);\n }\n\n setActiveConfig(activeConfig: FirebaseRemoteConfigObject): Promise<void> {\n this.activeConfig = activeConfig;\n return this.storage.setActiveConfig(activeConfig);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RemoteConfig } from './public_types';\nimport { activate, fetchConfig } from './api';\nimport {\n getModularInstance,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\n\n// This API is put in a separate file, so we can stub fetchConfig and activate in tests.\n// It's not possible to stub standalone functions from the same module.\n/**\n *\n * Performs fetch and activate operations, as a convenience.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n *\n * @returns A `Promise` which resolves to true if the current call activated the fetched configs.\n * If the fetched configs were already activated, the `Promise` will resolve to false.\n *\n * @public\n */\nexport async function fetchAndActivate(\n remoteConfig: RemoteConfig\n): Promise<boolean> {\n remoteConfig = getModularInstance(remoteConfig);\n await fetchConfig(remoteConfig);\n return activate(remoteConfig);\n}\n\n/**\n * This method provides two different checks:\n *\n * 1. Check if IndexedDB exists in the browser environment.\n * 2. Check if the current browser context allows IndexedDB `open()` calls.\n *\n * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance\n * can be initialized in this environment, or false if it cannot.\n * @public\n */\nexport async function isSupported(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n try {\n const isDBOpenable: boolean = await validateIndexedDBOpenable();\n return isDBOpenable;\n } catch (error) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { isIndexedDBAvailable } from '@firebase/util';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { RemoteConfig } from './public_types';\nimport { name as packageName, version } from '../package.json';\nimport { ensureInitialized } from './api';\nimport { CachingClient } from './client/caching_client';\nimport { RestClient } from './client/rest_client';\nimport { RetryingClient } from './client/retrying_client';\nimport { RC_COMPONENT_NAME } from './constants';\nimport { ErrorCode, ERROR_FACTORY } from './errors';\nimport { RemoteConfig as RemoteConfigImpl } from './remote_config';\nimport { Storage } from './storage/storage';\nimport { StorageCache } from './storage/storage_cache';\n// This needs to be in the same file that calls `getProvider()` on the component\n// or it will get tree-shaken out.\nimport '@firebase/installations';\n\nexport function registerRemoteConfig(): void {\n _registerComponent(\n new Component(\n RC_COMPONENT_NAME,\n remoteConfigFactory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n\n registerVersion(packageName, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(packageName, version, '__BUILD_TARGET__');\n\n function remoteConfigFactory(\n container: ComponentContainer,\n { instanceIdentifier: namespace }: InstanceFactoryOptions\n ): RemoteConfig {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n // The following call will always succeed because rc has `import '@firebase/installations'`\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\n // Guards against the SDK being used in non-browser environments.\n if (typeof window === 'undefined') {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_WINDOW);\n }\n // Guards against the SDK being used when indexedDB is not available.\n if (!isIndexedDBAvailable()) {\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNAVAILABLE);\n }\n // Normalizes optional inputs.\n const { projectId, apiKey, appId } = app.options;\n if (!projectId) {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_PROJECT_ID);\n }\n if (!apiKey) {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_API_KEY);\n }\n if (!appId) {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_APP_ID);\n }\n namespace = namespace || 'firebase';\n\n const storage = new Storage(appId, app.name, namespace);\n const storageCache = new StorageCache(storage);\n\n const logger = new Logger(packageName);\n\n // Sets ERROR as the default log level.\n // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level.\n logger.logLevel = FirebaseLogLevel.ERROR;\n\n const restClient = new RestClient(\n installations,\n // Uses the JS SDK version, by which the RC package version can be deduced, if necessary.\n SDK_VERSION,\n namespace,\n projectId,\n apiKey,\n appId\n );\n const retryingClient = new RetryingClient(restClient, storage);\n const cachingClient = new CachingClient(\n retryingClient,\n storage,\n storageCache,\n logger\n );\n\n const remoteConfigInstance = new RemoteConfigImpl(\n app,\n cachingClient,\n storageCache,\n storage,\n logger\n );\n\n // Starts warming cache.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n ensureInitialized(remoteConfigInstance);\n\n return remoteConfigInstance;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport {\n Value as ValueCompat,\n FetchStatus as FetchSTatusCompat,\n Settings as SettingsCompat,\n LogLevel as RemoteConfigLogLevel,\n RemoteConfig as RemoteConfigCompat\n} from '@firebase/remote-config-types';\nimport {\n RemoteConfig,\n setLogLevel,\n activate,\n ensureInitialized,\n fetchAndActivate,\n fetchConfig,\n getAll,\n getBoolean,\n getNumber,\n getString,\n getValue,\n isSupported\n} from '@firebase/remote-config';\n\nexport { isSupported };\n\nexport class RemoteConfigCompatImpl\n implements RemoteConfigCompat, _FirebaseService\n{\n constructor(public app: FirebaseApp, readonly _delegate: RemoteConfig) {}\n\n get defaultConfig(): { [key: string]: string | number | boolean } {\n return this._delegate.defaultConfig;\n }\n\n set defaultConfig(value: { [key: string]: string | number | boolean }) {\n this._delegate.defaultConfig = value;\n }\n\n get fetchTimeMillis(): number {\n return this._delegate.fetchTimeMillis;\n }\n\n get lastFetchStatus(): FetchSTatusCompat {\n return this._delegate.lastFetchStatus;\n }\n\n get settings(): SettingsCompat {\n return this._delegate.settings;\n }\n\n set settings(value: SettingsCompat) {\n this._delegate.settings = value;\n }\n\n activate(): Promise<boolean> {\n return activate(this._delegate);\n }\n\n ensureInitialized(): Promise<void> {\n return ensureInitialized(this._delegate);\n }\n\n /**\n * @throws a {@link ErrorCode.FETCH_CLIENT_TIMEOUT} if the request takes longer than\n * {@link Settings.fetchTimeoutInSeconds} or\n * {@link DEFAULT_FETCH_TIMEOUT_SECONDS}.\n */\n fetch(): Promise<void> {\n return fetchConfig(this._delegate);\n }\n\n fetchAndActivate(): Promise<boolean> {\n return fetchAndActivate(this._delegate);\n }\n\n getAll(): { [key: string]: ValueCompat } {\n return getAll(this._delegate);\n }\n\n getBoolean(key: string): boolean {\n return getBoolean(this._delegate, key);\n }\n\n getNumber(key: string): number {\n return getNumber(this._delegate, key);\n }\n\n getString(key: string): string {\n return getString(this._delegate, key);\n }\n\n getValue(key: string): ValueCompat {\n return getValue(this._delegate, key);\n }\n\n // Based on packages/firestore/src/util/log.ts but not static because we need per-instance levels\n // to differentiate 2p and 3p use-cases.\n setLogLevel(logLevel: RemoteConfigLogLevel): void {\n setLogLevel(this._delegate, logLevel);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconsole.warn(`\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n`);\n\nimport firebase from './app';\nimport { name, version } from '../package.json';\n\nimport './analytics';\nimport './app-check';\nimport './auth';\nimport './database';\nimport './firestore';\nimport './functions';\nimport './messaging';\nimport './storage';\nimport './performance';\nimport './remote-config';\n\nfirebase.registerVersion(name, version, 'compat-cdn');\n\nexport default firebase;\n"],"names":["base64Encode","str","utf8Bytes","stringToByteArray","base64","encodeByteArray","CONSTANTS","NODE_CLIENT","NODE_ADMIN","SDK_VERSION","assert","assertion","message","assertionError","Error","out","p","i","length","c","charCodeAt","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","input","webSafe","Array","isArray","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c2","c3","c1","String","fromCharCode","u","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","base64urlEncodeWithoutPadding","replace","base64Decode","e","console","error","deepExtend","target","source","Object","constructor","Date","dateValue","getTime","undefined","prop","hasOwnProperty","getGlobal","self","window","global","getDefaultsFromGlobal","__FIREBASE_DEFAULTS__","getDefaultsFromEnvVariable","process","env","defaultsJsonString","JSON","parse","getDefaultsFromCookie","document","match","cookie","decoded","getDefaults","info","getDefaultAppConfig","_a","config","LogLevel","Deferred","reject","resolve","promise","Promise","wrapCallback","callback","value","catch","createMockUserToken","token","projectId","uid","project","iat","sub","user_id","payload","assign","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","stringify","alg","type","getUA","navigator","isMobileCordova","test","isNode","forceEnvironment","prototype","toString","call","isBrowserExtension","runtime","chrome","browser","id","isReactNative","isIE","ua","indexOf","isNodeSdk","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","open","onsuccess","result","close","deleteDatabase","onupgradeneeded","onerror","areCookiesEnabled","cookieEnabled","FirebaseError","code","customData","super","name","setPrototypeOf","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","PATTERN","_","key","fullMessage","jsonEval","decode","header","claims","signature","parts","split","contains","obj","safeGet","isEmpty","map","fn","contextObj","res","deepEqual","a","b","aKeys","keys","bKeys","k","includes","aProp","bProp","isObject","thing","querystring","querystringParams","params","entries","forEach","arrayVal","encodeURIComponent","querystringDecode","tokens","decodeURIComponent","extractQuerystring","url","queryStart","fragmentStart","substring","Sha1","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","offset","W","t","d","f","update","lengthMinusBlock","n","inbuf","digest","totalBits","j","createSubscribe","executor","onNoObservers","proxy","ObserverProxy","subscribe","bind","observers","unsubscribes","observerCount","task","finalized","then","next","forEachObserver","observer","complete","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","err","validateArgCount","fnName","minCount","maxCount","argCount","argError","errorPrefix","argName","validateCallback","argumentName","optional","validateContextObject","context","uuidv4","r","Math","random","v","stringLength","DEFAULT_INTERVAL_MILLIS","DEFAULT_BACKOFF_FACTOR","MAX_VALUE_MILLIS","RANDOM_FACTOR","calculateBackoffMillis","backoffCount","intervalMillis","backoffFactor","currBaseValue","pow","randomWait","round","min","getModularInstance","_delegate","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","get","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","set","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","options","getComponent","setComponent","instanceDeferred","clearInstance","delete","services","from","values","all","filter","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","Set","add","existingInstance","invokeOnInitCallbacks","callbacks","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","now","toISOString","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","instanceOfAny","object","constructors","some","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","apply","unwrap","storeNames","tx","sort","transformCachableValue","done","unlisten","removeEventListener","DOMException","addEventListener","IDBObjectStore","IDBIndex","Proxy","IDBRequest","success","promisifyRequest","newValue","openDB","version","blocked","upgrade","blocking","terminated","openPromise","event","oldVersion","newVersion","db","deleteDB","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","async","storeName","store","index","shift","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","library","logString","logger","variant","PLATFORM_LOG_STRING","@firebase/app","@firebase/app-compat","@firebase/analytics","@firebase/analytics-compat","@firebase/app-check","@firebase/app-check-compat","@firebase/auth","@firebase/auth-compat","@firebase/database","@firebase/database-compat","@firebase/functions","@firebase/functions-compat","@firebase/installations","@firebase/installations-compat","@firebase/messaging","@firebase/messaging-compat","@firebase/performance","@firebase/performance-compat","@firebase/remote-config","@firebase/remote-config-compat","@firebase/storage","@firebase/storage-compat","@firebase/firestore","@firebase/firestore-compat","fire-js","_apps","_components","_addComponent","app","_addOrOverwriteComponent","_registerComponent","componentName","_getProvider","heartbeatController","triggerHeartbeat","ERROR_FACTORY","no-app","bad-app-name","duplicate-app","app-deleted","no-options","invalid-app-argument","invalid-log-argument","idb-open","idb-get","idb-set","idb-delete","FirebaseAppImpl","_isDeleted","_options","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","initializeApp","rawConfig","existingApp","newApp","getApp","deleteApp","registerVersion","libraryKeyOrName","libraryMismatch","versionMismatch","warning","onLog","logCallback","customLogLevel","level","arg","ignored","toLowerCase","setUserLogHandler","inst","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","platformLogger","agent","date","getUTCDateString","lastSentHeartbeatDate","heartbeats","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","slice","heartbeatEntry","find","hb","dates","countBytes","pop","extractHeartbeatsForHeader","headerString","today","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","clear","removeApp","_getService","_DEFAULT_ENTRY_NAME","_removeServiceInstance","toJSON","createFirebaseNamespaceCore","firebaseAppImpl","apps","namespace","__esModule","modularAPIs.initializeApp","appCompat","modularAPIs.registerVersion","modularAPIs.setLogLevel","modularAPIs.onLog","modularAPIs.SDK_VERSION","registerComponent","componentNameWithoutCompat","serviceNamespace","modularAPIs._registerComponent","appArg","serviceFxn","useAsService","useService","modularAPIs","modularAPIs._DEFAULT_ENTRY_NAME","defineProperty","createFirebaseNamespace","extendNamespace","sdkVersion","firebaseNamespace","registerCoreComponents","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","missing-app-config-values","not-registered","installation-not-found","request-failed","app-offline","delete-pending-registration","isServerError","getInstallationsEndpoint","extractAuthTokenInfoFromResponse","response","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","apiKey","Headers","Content-Type","Accept","x-goog-api-key","getHeadersWithAuth","appConfig","refreshToken","headers","append","retryIfServerError","sleep","ms","setTimeout","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","Uint8Array","crypto","msCrypto","getRandomValues","fid","b64String","array","b64","bufferToBase64UrlSafe","substr","encode","getKey","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","broadcastChannel","BroadcastChannel","onmessage","getBroadcastChannel","postMessage","size","broadcastFidChange","OBJECT_STORE_NAME","oldValue","remove","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","clearTimedOutRequest","registrationStatus","entryWithPromise","entry","updateInstallationRequest","waitUntilFidRegistration","onLine","registrationPromiseWithError","inProgressEntry","registrationTime","registeredInstallationEntry","heartbeatServiceProvider","endpoint","heartbeatService","heartbeatsHeader","body","authVersion","fetch","ok","responseValue","authToken","createInstallationRequest","registerInstallation","triggerRegistrationIfNecessary","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenExpired","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","updatedInstallationEntry","fetchAuthTokenFromServer","getToken","installationsImpl","getMissingValueError","valueName","INSTALLATIONS_NAME","publicFactory","keyName","extractAppConfig","internalFactory","getId","ANALYTICS_TYPE","GA_FID_KEY","ORIGIN_KEY","DYNAMIC_CONFIG_URL","GTAG_URL","promiseAllSettled","promises","wrapGtag","gtagCore","initializationPromisesMap","dynamicConfigPromisesList","measurementIdToAppId","command","idOrNameOrParams","gtagParams","measurementId","initializationPromisesToWaitFor","gaSendToList","dynamicConfigResults","sendToId","foundConfig","initializationPromise","gtagOnEvent","correspondingAppId","gtagOnConfig","already-exists","already-initialized","already-initialized-settings","interop-component-reg-failed","invalid-analytics-context","indexeddb-unavailable","fetch-throttle","config-fetch-failed","no-api-key","no-app-id","LONG_RETRY_FACTOR","defaultRetryData","throttleMetadata","getThrottleMetadata","setThrottleMetadata","metadata","deleteThrottleMetadata","fetchDynamicConfig","appFields","appUrl","errorMessage","jsonResponse","_ignored","httpStatus","responseMessage","fetchDynamicConfigWithRetry","retryData","timeoutMillis","throttleEndTimeMillis","signal","AnalyticsAbortSignal","abort","attemptFetchDynamicConfigWithRetry","setAbortableTimeout","isRetriableError","backoffMillis","max","timeout","clearTimeout","listeners","listener","_initializeAnalytics","dataLayerName","dynamicConfigPromise","fidPromise","errorInfo","validateIndexedDB","envIsValid","dynamicConfig","scriptTags","getElementsByTagName","tag","src","findGtagScriptOnPage","script","createElement","head","appendChild","insertScriptTag","configProperties","AnalyticsService","gtagName","gtagCoreFunction","wrappedGtagFunction","globalInitDone","settings","factory","mismatchedEnvMessages","details","warnOnBrowserContextMismatch","wrappedGtag","dataLayer","getOrCreateDataLayer","gtagFunctionName","arguments","wrapOrCreateGtag","isSupported","setCurrentScreen","analyticsInstance","screenName","gtagFunction","screen_name","internalSetCurrentScreen","setUserId","internalSetUserId","setUserProperties","properties","flatProperties","user_properties","internalSetUserProperties","setAnalyticsCollectionEnabled","enabled","internalSetAnalyticsCollectionEnabled","logEvent","eventName","eventParams","send_to","internalLogEvent","analyticsOptions","analytics","reason","EventName","namespaceExports","logEventExp","setCurrentScreenExp","setUserIdExp","setUserPropertiesExp","setAnalyticsCollectionEnabledExp","analyticsServiceExp","Analytics","settingsExp","isSupportedExp","APP_CHECK_STATES","DEFAULT_STATE","activated","tokenObservers","DEBUG_STATE","initialized","getStateReference","BASE_ENDPOINT","EXCHANGE_DEBUG_TOKEN_METHOD","TOKEN_REFRESH_TIME","OFFSET_DURATION","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","Refresher","operation","retryPolicy","getWaitDuration","lowerBound","upperBound","pending","nextErrorWaitInterval","start","stop","isRunning","hasSucceeded","getNextRun","currentErrorWaitInterval","use-before-activation","fetch-network-error","fetch-parse-error","fetch-status-error","storage-open","storage-get","storage-set","recaptcha-error","throttled","getRecaptcha","isEnterprise","grecaptcha","enterprise","ensureActivated","getDurationString","durationInMillis","totalSeconds","days","floor","hours","minutes","seconds","pad","exchangeToken","originalError","responseBody","ttl","isNaN","timeToLiveAsNumber","expireTimeMillis","issuedAtTimeMillis","DEBUG_TOKEN_KEY","getDBPromise","keyPath","write","compositeKey","_event","readTokenFromStorage","writeTokenToStorage","readOrCreateDebugTokenFromStorage","existingDebugToken","_e","newToken","isDebugMode","getDebugToken","state","defaultTokenErrorData","appCheck","isValid","cachedToken","cachedTokenPromise","shouldCallListeners","exchangeTokenPromise","debugToken","debug_token","getExchangeDebugTokenRequest","finally","tokenFromDebugExchange","interopTokenResult","internalError","makeDummyTokenResult","notifyTokenListeners","addTokenListener","onError","tokenObserver","validToken","initTokenRefresher","removeTokenListener","newObservers","tokenRefresher","refresher","nextRefreshTimeMillis","latestAllowableRefresh","createTokenRefresher","isTokenAutoRefreshEnabled","tokenErrorData","AppCheckService","RECAPTCHA_URL","RECAPTCHA_ENTERPRISE_URL","initializeV3","siteKey","reCAPTCHAState","divId","makeDiv","queueWidgetRender","onload","loadReCAPTCHAV3Script","initializeEnterprise","loadReCAPTCHAEnterpriseScript","ready","widgetId","render","sitekey","renderInvisibleWidget","invisibleDiv","style","display","recaptcha","_reject","execute","action","ReCaptchaV3Provider","_siteKey","_throttleData","throwIfThrottled","attestedClaimsToken","getReCAPTCHAToken","_app","reCAPTCHAToken","recaptcha_v3_token","getExchangeRecaptchaV3TokenRequest","_heartbeatServiceProvider","setBackoff","_b","time","allowRequestsAfter","initializeRecaptchaV3","isEqual","otherProvider","ReCaptchaEnterpriseProvider","recaptcha_enterprise_token","getExchangeRecaptchaEnterpriseTokenRequest","initializeRecaptchaEnterprise","CustomProvider","_customProviderOptions","customToken","issuedAtTimeSeconds","issuedAtTime","throttleData","initializeAppCheck","globals","debugState","FIREBASE_APPCHECK_DEBUG_TOKEN","deferredToken","initializeDebugMode","initialOptions","setInitialState","_activate","APP_CHECK_NAME_INTERNAL","_identifier","_appcheckService","activate","siteKeyOrProvider","setTokenAutoRefreshEnabled","appCheckInstance","setTokenAutoRefreshEnabledExp","getTokenInternal","getTokenExp","onTokenChanged","onNextOrObserver","onCompletion","nextFn","errorFn","onTokenChangedExp","__rest","s","getOwnPropertySymbols","propertyIsEnumerable","ProviderId","FACEBOOK","GITHUB","GOOGLE","PASSWORD","PHONE","TWITTER","ActionCodeOperation","EMAIL_SIGNIN","PASSWORD_RESET","RECOVER_EMAIL","REVERT_SECOND_FACTOR_ADDITION","VERIFY_AND_CHANGE_EMAIL","VERIFY_EMAIL","_prodErrorMap","dependent-sdk-initialized-before-auth","debugErrorMap","admin-restricted-operation","argument-error","app-not-authorized","app-not-installed","captcha-check-failed","code-expired","cordova-not-ready","cors-unsupported","credential-already-in-use","custom-token-mismatch","requires-recent-login","dynamic-link-not-activated","email-change-needs-verification","email-already-in-use","emulator-config-failed","expired-action-code","cancelled-popup-request","internal-error","invalid-app-credential","invalid-app-id","invalid-user-token","invalid-auth-event","invalid-verification-code","invalid-continue-uri","invalid-cordova-configuration","invalid-custom-token","invalid-dynamic-link-domain","invalid-email","invalid-emulator-scheme","invalid-api-key","invalid-cert-hash","invalid-credential","invalid-message-payload","invalid-multi-factor-session","invalid-oauth-provider","invalid-oauth-client-id","unauthorized-domain","invalid-action-code","wrong-password","invalid-persistence-type","invalid-phone-number","invalid-provider-id","invalid-recipient-email","invalid-sender","invalid-verification-id","invalid-tenant-id","login-blocked","missing-android-pkg-name","auth-domain-config-required","missing-app-credential","missing-verification-code","missing-continue-uri","missing-iframe-start","missing-ios-bundle-id","missing-or-invalid-nonce","missing-multi-factor-info","missing-multi-factor-session","missing-phone-number","missing-verification-id","multi-factor-info-not-found","multi-factor-auth-required","account-exists-with-different-credential","network-request-failed","no-auth-event","no-such-provider","null-user","operation-not-allowed","operation-not-supported-in-this-environment","popup-blocked","popup-closed-by-user","provider-already-linked","quota-exceeded","redirect-cancelled-by-user","redirect-operation-pending","rejected-credential","second-factor-already-in-use","maximum-second-factor-count-exceeded","tenant-id-mismatch","user-token-expired","too-many-requests","unauthorized-continue-uri","unsupported-first-factor","unsupported-persistence-type","unsupported-tenant-operation","unverified-email","user-cancelled","user-not-found","user-disabled","user-mismatch","user-signed-out","weak-password","web-storage-unsupported","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","_assertInstanceOf","fullParams","_errorFactory","_assert","debugFail","failure","debugAssert","instanceCache","_getInstance","cls","Function","_getCurrentUrl","location","href","_isHttpOrHttps","_getCurrentScheme","protocol","Delay","shortDelay","longDelay","isMobile","_emulatorUrl","path","emulator","startsWith","FetchProvider","fetchImpl","headersImpl","responseImpl","Response","SERVER_ERROR_MAP","CREDENTIAL_MISMATCH","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_CONTINUE_URI","INVALID_PASSWORD","MISSING_PASSWORD","EMAIL_EXISTS","PASSWORD_LOGIN_DISABLED","INVALID_IDP_RESPONSE","INVALID_PENDING_TOKEN","FEDERATED_USER_ID_ALREADY_LINKED","MISSING_REQ_TYPE","EMAIL_NOT_FOUND","RESET_PASSWORD_EXCEED_LIMIT","EXPIRED_OOB_CODE","INVALID_OOB_CODE","MISSING_OOB_CODE","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","INVALID_ID_TOKEN","TOKEN_EXPIRED","USER_NOT_FOUND","TOO_MANY_ATTEMPTS_TRY_LATER","INVALID_CODE","INVALID_SESSION_INFO","INVALID_TEMPORARY_PROOF","MISSING_SESSION_INFO","SESSION_EXPIRED","MISSING_ANDROID_PACKAGE_NAME","UNAUTHORIZED_DOMAIN","INVALID_OAUTH_CLIENT_ID","ADMIN_ONLY_OPERATION","INVALID_MFA_PENDING_CREDENTIAL","MFA_ENROLLMENT_NOT_FOUND","MISSING_MFA_ENROLLMENT_ID","MISSING_MFA_PENDING_CREDENTIAL","SECOND_FACTOR_EXISTS","SECOND_FACTOR_LIMIT_EXCEEDED","BLOCKING_FUNCTION_ERROR_RESPONSE","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","query","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","_makeTaggedError","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_serverResponse","host","base","apiScheme","timer","errorParams","email","phoneNumber","_tokenResponse","utcTimestampToDateString","utcTimestamp","toUTCString","secondsStringToMilliseconds","_parseToken","algorithm","_logoutIfInvalidated","user","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","_copy","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","original","newData","newProviderData","providerUserInfo","providerId","rawId","displayName","photoURL","photoUrl","providerData","o","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","emailVerified","StsTokenManager","accessToken","isExpired","updateFromServerResponse","parsedToken","updateTokensAndExpiration","refresh","clearRefreshToken","oldToken","grant_type","refresh_token","tokenApiHost","access_token","expires_in","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","signInProvider","authTime","signInSecondFactor","reload","userInfo","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_c","_d","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_key","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","queue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","AuthImpl","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","lastNotifiedUid","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","redirectUserEventId","storedUserEventId","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","tryRedirectSignIn","directlySetCurrentUser","reloadAndSetCurrentUserOrClear","_overrideRedirectResult","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","cb","addObserver","_logFramework","framework","_getFrameworks","X-Client-Version","_castAuth","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","port","authority","exec","hostAndPort","bracketedIPv6","parsePort","extractHostAndPort","freeze","attachBanner","el","sty","innerText","position","width","backgroundColor","border","color","bottom","left","margin","zIndex","textAlign","classList","readyState","emitEmulatorWarning","protocolEnd","portStr","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","resetPassword","updateEmailPassword","sendOobCode","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","password","_fromEmailAndCode","oobCode","signInWithPassword","returnSecureToken","signInWithEmailLink","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber","_makeVerificationRequest","linkWithPhoneNumber","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","link","doubleDeepLink","iOSDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","OAuthProvider","credentialFromJSON","_credential","rawNonce","credentialFromResult","userCredential","oauthCredentialFromTaggedObject","credentialFromError","tokenResponse","oauthIdToken","oauthAccessToken","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromTaggedObject","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","SAMLAuthCredential","_create","SAMLAuthProvider","samlCredentialFromTaggedObject","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","signUp","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","idTokenProvider","providerDataAsNames","pid","unlink","_assertLinkedStatus","deleteProvider","providersLeft","pd","_link","expected","providerIds","_reauthenticate","parsed","_signInWithCredential","signInWithCredential","linkWithCredential","reauthenticateWithCredential","signInWithCustomToken","MultiFactorInfoImpl","factorId","mfaEnrollmentId","enrollmentTime","enrolledAt","_fromServerResponse","enrollment","PhoneMultiFactorInfoImpl","phoneInfo","_setActionCodeSettingsOnRequest","actionCodeSettings","dynamicLinkDomain","canHandleCodeInApp","handleCodeInApp","iOS","bundleId","iOSBundleId","android","packageName","androidInstallApp","installApp","androidMinimumVersionCode","minimumVersion","androidPackageName","sendPasswordResetEmail","authModular","requestType","applyActionCode","checkActionCode","account.resetPassword","newEmail","mfaInfo","multiFactorInfo","previousEmail","sendSignInLinkToEmail","fetchSignInMethodsForEmail","continueUri","signinMethods","sendEmailVerification","verifyBeforeUpdateEmail","updateProfile","apiUpdateProfile","passwordProvider","updateEmailOrPassword","apiUpdateEmailPassword","GenericAdditionalUserInfo","isNewUser","profile","FederatedAdditionalUserInfoWithUsername","username","FacebookAdditionalUserInfo","GithubAdditionalUserInfo","login","GoogleAdditionalUserInfo","TwitterAdditionalUserInfo","getAdditionalUserInfo","rawUserInfo","kind","filteredProviderId","MultiFactorSessionImpl","_fromIdtoken","_fromMfaPendingCredential","mfaPendingCredential","multiFactorSession","pendingCredential","MultiFactorResolverImpl","session","hints","signInResolver","_fromError","authExtern","mfaResponse","_process","resolveSignIn","assertionExtern","MultiFactorUserImpl","enrolledFactors","_fromUser","getSession","enroll","finalizeMfaResponse","unenroll","infoOrUid","multiFactorUserCache","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","poll","onStorageEvent","localCache","pollTimer","safariLocalStorageNotSynced","top","_isIframe","fallbackToPolling","forAllChangedKeys","detachListener","stopPolling","storedValue","triggerListeners","notifyListeners","documentMode","_oldValue","startPolling","setInterval","StorageEvent","clearInterval","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","handler","origin","fulfilled","_subscribe","eventHandler","_unsubscribe","_generateEventId","prefix","digits","Sender","removeMessageHandler","messageChannel","port1","onMessage","_send","MessageChannel","completionTimer","ackTimer","port2","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","_putObject","fbase_key","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","_poll","keyProcessed","_data","results","serviceWorker","active","_getActiveServiceWorker","notifyServiceWorker","controller","_withPendingWrite","getObject","getAllRequest","getAll","keysInResult","localKey","indexedDBLocalPersistence","_loadJS","setAttribute","charset","_generateCallbackName","MockReCaptcha","counter","_widgets","parameters","MockWidget","optWidgetId","getResponse","containerOrId","deleted","responseToken","clickHandler","getElementById","isVisible","checkIfDeleted","len","chars","allowedChars","generateRandomAlphaNumericString","expired-callback","expiredCallback","_JSLOAD_CALLBACK","jsHelpers._generateCallbackName","NETWORK_TIMEOUT_DELAY","ReCaptchaLoaderImpl","hostLanguage","librarySeparatelyLoaded","load","hl","shouldResolveImmediately","jsHelpers._loadJS","clearedOneInstance","MockReCaptchaLoaderImpl","RECAPTCHA_VERIFIER_TYPE","DEFAULT_PARAMS","theme","RecaptchaVerifier","destroyed","tokenChangeListeners","renderPromise","isInvisible","makeTokenCallback","_recaptchaLoader","validateStartingState","verify","assertNotDestroyed","getAssertedRecaptcha","tokenChange","makeRenderPromise","_reset","childNodes","node","removeChild","hasChildNodes","existing","globalFunc","init","guaranteedEmpty","domReady","recaptchaSiteKey","ConfirmationResultImpl","onConfirmation","confirm","authCredential","_verifyPhoneNumber","verifier","recaptchaToken","phoneInfoOptions","phoneEnrollmentInfo","phoneSessionInfo","multiFactorHint","multiFactorUid","phoneSignInInfo","phoneResponseInfo","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","_linkUser","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","_setPendingRedirectStatus","signInWithRedirect","resolverInternal","_openRedirect","_signInWithRedirect","reauthenticateWithRedirect","prepareUserForRedirect","_reauthenticateWithRedirect","linkWithRedirect","_linkWithRedirect","_getRedirectResult","resolverExtern","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","eventUid","_getProjectConfig","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","domain","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","re","RegExp","matchDomain","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","H","hint","L","CP","cachedGApiLoader","_loadGapi","loadGapiIframe","gapi","iframes","getContext","ontimeout","Iframe","cbName","js._generateCallbackName","js\r\n ._loadJS","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","height","aria-hidden","tabindex","EID_FROM_APIHOST","_openIframe","gapiLoader._loadGapi","where","eid","fw","getIframeUrl","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","iframe","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","_open","screen","availHeight","availWidth","scrollbars","optionsString","reduce","accum","_isIOSStandalone","standalone","click","createEvent","initMouseEvent","dispatchEvent","openAsNewWindowIOS","newWin","focus","WIDGET_PATH","EMULATOR_WIDGET_PATH","_getRedirectUrl","authType","redirectUrl","additionalParams","tid","paramsDict","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","initAndGetManager","register","iframeEvent","authEvent","send","PhoneMultiFactorAssertionImpl","_finalizeEnroll","_finalizeSignIn","_fromCredential","phoneVerificationInfo","PhoneMultiFactorGenerator","FACTOR_ID","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","unsubscribe","updateProactiveRefresh","removeAuthTokenListener","_cordovaWindow","deps","authInstance","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","authInternalProvider","getVersionForPlatform","_generateHandlerUrl","BuildInfo","sessionDigest","TextEncoder","buff","ArrayBuffer","view","stringToArrayBuffer","subtle","arr","num","padStart","computeSha256","_performRedirect","handlerUrl","cordova","plugins","browsertab","isAvailable","browserTabIsAvailable","iabRef","openUrl","InAppBrowser","SESSION_ID_LENGTH","CordovaAuthEventManager","passiveListeners","initPromise","resolveInialized","addPassiveListener","removePassiveListener","resetRedirect","_generateNewEvent","idx","generateSessionId","_getAndRemoveEvent","persistenceKey","_eventFromPartialAndUrl","partialEvent","callbackUrl","searchParamsOrEmpty","iOSDoubleDeepLink","errorObject","parseJsonOrNull","cordovaPopupRedirectResolver","attachCallbackListeners","win","universalLinks","missingPlugin","_k","_j","eventListener","cleanup","onCloseTimer","authEventSeen","closeBrowserTab","resumed","visibilityChanged","visibilityState","_waitForAppResume","_cb","iosBundleId","handleOpenURL","noEventTimeout","generateNoEvent","universalLinksCb","eventData","finalEvent","existingHandleOpenURL","packagePrefix","_isAndroidOrIosCordovaScheme","_isLocalStorageNotSynchronized","_isEdge","_isWebStorageSupported","impl","_isPopupRedirectSupported","_isLikelyCordova","Persistence","LOCAL","NONE","SESSION","exp._assert","PERSISTENCE_KEY","_savePersistenceForRedirect","getSessionStorageIfAvailable","exp._persistenceKeyName","CompatPopupRedirectResolver","browserResolver","exp._getInstance","exp.browserPopupRedirectResolver","cordovaResolver","exp.cordovaPopupRedirectResolver","underlyingResolver","exp.browserSessionPersistence","exp._getRedirectResult","exp._overrideRedirectResult","selectUnderlyingResolver","assertedUnderlyingResolver","isCordova","timeoutId","attachExtraErrorFields","mfaErr","MultiFactorResolver","errorInternal","credentialFromObject","credErr","exp.PhoneAuthProvider","exp.ProviderId","exp.GoogleAuthProvider","exp.FacebookAuthProvider","exp.GithubAuthProvider","exp.TwitterAuthProvider","exp.SAMLAuthCredential","exp.OAuthCredential","exp.OAuthProvider","convertCredential","credentialPromise","additionalUserInfo","exp.getAdditionalUserInfo","User","getOrCreate","convertConfirmationResult","confirmationResultPromise","confirmationResultExp","wrapped","userModular","multiFactor","USER_MAP","linkAndRetrieveDataWithCredential","exp.linkWithCredential","appVerifier","exp.linkWithPhoneNumber","linkWithPopup","exp.linkWithPopup","exp._castAuth","exp.linkWithRedirect","reauthenticateAndRetrieveDataWithCredential","exp.reauthenticateWithCredential","reauthenticateWithPhoneNumber","exp.reauthenticateWithPhoneNumber","reauthenticateWithPopup","exp.reauthenticateWithPopup","exp.reauthenticateWithRedirect","exp.sendEmailVerification","exp.unlink","updateEmail","updatePassword","newPassword","updatePhoneNumber","phoneCredential","exp.updatePhoneNumber","exp.updateProfile","exp.verifyBeforeUpdateEmail","Auth","linkUnderlyingAuth","persistences","exp.inMemoryPersistence","exp.indexedDBLocalPersistence","_getPersistencesFromRedirect","exp.browserLocalPersistence","buildPersistenceHierarchy","exp.debugErrorMap","useEmulator","exp.connectAuthEmulator","exp.applyActionCode","exp.checkActionCode","confirmPasswordReset","exp.confirmPasswordReset","createUserWithEmailAndPassword","exp.createUserWithEmailAndPassword","fetchProvidersForEmail","exp.fetchSignInMethodsForEmail","isSignInWithEmailLink","getRedirectResult","addFrameworkForLogging","wrapObservers","exp.sendSignInLinkToEmail","exp.sendPasswordResetEmail","converted","isIndexedDBFullySupported","exp\r\n ._getInstance","exp._fail","signInAndRetrieveDataWithCredential","signInAnonymously","exp.signInAnonymously","exp.signInWithCredential","exp.signInWithCustomToken","signInWithEmailAndPassword","exp.signInWithEmailLink","exp.signInWithPhoneNumber","signInWithPopup","exp.signInWithPopup","exp.signInWithRedirect","verifyPasswordResetCode","exp.verifyPasswordResetCode","oldNext","exp.RecaptchaVerifier","authProvider","ActionCodeInfo","Operation","CompatAuthProvider","CompatRecaptchaVerifier","setSDKVersion","DOMStorageWrapper","domStorage_","prefix_","prefixedName_","storedVal","MemoryStorage","cache_","isInMemoryStorage","OperationType","createStoragefor","domStorageName","domStorage","sha1","high","low","sha1Bytes","PersistentStorage","SessionStorage","LUIDGenerator","buildLogMessage_","varArgs","firstLog_","logWrapper","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","dataSegs","enableLogging","logger_","persistent","fatal","warnIfPageIsSecure","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","each","doubleToIEEE754String","ln","Infinity","abs","LN2","bits","hexByteString","hexByte","parseInt","INTEGER_REGEXP_","intVal","INTEGER_32_MIN","INTEGER_32_MAX","setTimeoutNonBlocking","Deno","unrefTimer","exceptionGuard","stack","AppCheckTokenProvider","appName_","appCheckProvider","addTokenChangeListener","notifyForInvalidToken","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth_","removeTokenChangeListener","EmulatorTokenProvider","OWNER","FORGE_DOMAIN_RE","WEBSOCKET","LONG_POLLING","RepoInfo","secure","webSocketOnly","nodeAdmin","includeNamespaceInQueryParams","_host","_domain","internalHost","isCacheableHost","isCustomHost","newHost","toURLString","repoInfoConnectionURL","repoInfo","connURL","pairs","StatsCollection","counters_","incrementCounter","amount","collections","reporters","statsManagerGetCollection","hashString","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","handleResponse","requestNum","toProcess","BrowserPollConnection","connId","applicationId","appCheckToken","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","called","wrappedFn","attachEvent","executeWhenDOMReady","scriptTagHolder","FirebaseIFrameScriptHolder","arg1","arg2","incrementIncomingBytes_","sendNewPolls","pN","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","Windows","UI","markConnectionHealthy","shutdown_","myDisconnFrame","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","dframe","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","currentDomain","iframeContents","doc","contentWindow","contentDocument","alive","textContent","myID","myPW","newRequest_","theURL","curDataString","theSeg","seg","ts","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","loadCB","newScript","onreadystatechange","rstate","parentNode","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","mySock","onopen","onclose","m","handleIncomingFrame","isOldAndroid","oldAndroidMatch","parseFloat","previouslyFailed","appendFrame_","jsonMess","fullMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","remainingData","resetKeepAlive","sendString_","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","ALL_TRANSPORTS","IS_TRANSPORT_INITIALIZED","globalTransportInitialized_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports","transport","initialTransport","upgradeTransport","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","start_","conn","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeoutMS","healthyTimeout_","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","sendRequest","dataMsg","sendData_","tryCleanupConnection","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onDataMessage_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","h","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","closeConnections_","ServerActions","pathString","onComplete","hash","merge","refreshAppCheckToken","onDisconnectPut","onDisconnectMerge","onDisconnectCancel","reportStats","stats","EventEmitter","allowedEvents_","listeners_","trigger","on","validateEventType_","getInitialEvent","off","splice","et","OnlineMonitor","online_","getInstance","currentlyOnline","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","newEmptyPath","pathGetFront","pathGetLength","pathPopFront","pathGetBack","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathCompare","right","leftKeys","rightKeys","cmp","pathEquals","other","pathContains","ValidationPath","errorPrefix_","parts_","byteLength_","validationPathCheckValid","validationPath","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible_","visible","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens","outstandingPuts_","outstandingGets_","outstandingPutCount_","outstandingGetCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","forceTokenRefresh_","invalidAuthTokenCount_","invalidAppCheckTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","onVisible_","onOnline_","onResponse","curReqNum","initConnection_","_path","q","_queryObject","sendGet_","listen","currentHashFn","queryId","_queryIdentifier","_queryParams","isDefault","loadsAllData","listenSpec","hashFn","sendListen_","req","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","getIndex","tryAuth","reduceReconnectDelayIfAdminCredential_","tryAppCheck","authMethod","isValidFormat","requestData","onAuthRevoked_","onAppCheckRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","handleTimestamp_","sendConnectStats_","restoreState_","scheduleConnect_","establishConnection_","online","onRealtimeDisconnect_","reconnectDelay","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectAttempt","onDataMessage","onReady","nextConnectionId_","canceled","connection","closeFn","interrupt","resume","delta","serverTimeOffset","normalizedPathString","statusCode","explanation","queries","NamedNode","Wrap","Index","getCompare","compare","indexedValueChanged","oldNode","newNode","oldWrapped","newWrapped","minPost","MIN","__EMPTY_NODE","KeyIndex","isDefinedOn","maxPost","makePost","indexValue","KEY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","getNext","hasNext","peek","LLRBNode","RED","SortedMap","EMPTY_NODE","copy","count","inorderTraversal","reverseTraversal","min_","minKey","maxKey","insert","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","comparator_","root_","getPredecessorKey","rightParent","getIterator","resultGenerator","getIteratorFrom","getReverseIteratorFrom","getReverseIterator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE","priorityHashText","priority","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","LeafNode","value_","priorityNode_","lazyHash_","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","hasChild","getPredecessorChildName","childNode","updateImmediateChild","newChildNode","updateChild","front","numChildren","forEachChild","exportFormat",".value","getValue",".priority","toHash","compareTo","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","withIndex","isIndexed","equals","nodeFromJSON","PRIORITY_INDEX","aPriority","bPriority","indexCmp","LOG_2","Base12Num","current_","mask","bits_","nextBitIsOne","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","namedNode","middle","root","base12","buildPennant","chunkSize","childTree","pennant","attachPennant","isOne","buildFrom12Array","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","Default","indexKey","sortedMap","hasIndex","indexDefinition","addIndex","existingChildren","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","addToIndexes","indexedChildren","existingSnap","newChildren","removeFromIndexes","ChildrenNode","children_","indexMap_","child","newIndexMap","newPriority","newImmediateChild","numKeys","allIntegerKeys","childHash","resolveIndex_","predecessor","getFirstChildName","getFirstChild","getLastChildName","getLastChild","wrappedNode","startPost","iterator","endPost","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","USE_HINZE","jsonLeaf","childData","children","childrenHavePriority","childSet","sortedChildSet","PathIndex","indexPath_","extractChild","snap","aChild","bChild","valueNode","VALUE_INDEX","changeValue","snapshotNode","changeChildAdded","changeChildRemoved","changeChildChanged","oldSnap","IndexedFilter","index_","newChild","affectedPath","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","startIsInclusive_","startAfterSet_","endIsInclusive_","endBeforeSet_","getStartPost","getEndPost","isWithinStart","isWithinEnd","filtered","hasStart","startName","getIndexStartName","getIndexStartValue","hasEnd","endName","getIndexEndName","getIndexEndValue","LimitedFilter","withinDirectionalStart","reverse_","withinEndPost","withinStartPost","withinDirectionalEnd","compareRes","rangedFilter_","limit_","getLimit","isViewFromLeft","fullLimitUpdateChild_","childKey","childSnap","changeAccumulator","oldEventCache","newChildNamedNode","windowBoundary","inRange","oldChildSnap","nextChild","getChildAfterChild","compareNext","newEventCache","QueryParams","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","hasLimit","hasAnchoredLimit","queryParamsStartAt","queryParams","newParams","queryParamsEndAt","queryParamsOrderBy","queryParamsToRestQueryStringParameters","qs","orderBy","endParam","startParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listens_","getListenId_","listenId","thisListen","queryStringParameters","restRequest_","xhr","XMLHttpRequest","responseText","SnapshotHolder","rootNode_","getNode","updateSnapshot","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","sparseSnapshotTreeForEachTree","prefixPath","tree","StatsListener","collection_","last_","newStats","stat","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","reportedStats","haveStatsToReport","newOperationSourceUser","fromUser","fromServer","tagged","newOperationSourceServer","newOperationSourceServerTaggedQuery","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","operationForChild","subtree","ListenComplete","LISTEN_COMPLETE","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","EventGenerator","query_","eventGeneratorGenerateEventsForChanges","eventGenerator","changes","eventCache","eventRegistrations","events","moves","change","eventGeneratorGenerateEventsForType","registrations","filteredChanges","aWrapped","bWrapped","eventGeneratorCompareChanges","materializedChange","prevName","registration","respondsTo","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","ImmutableTree","fromObject","childPath","findRootMostMatchingPathAndValue","relativePath","predicate","childExistingPathAndValue","findRootMostValueAndPath","toSet","setTree","newTree","fold","fold_","pathSoFar","findOnPath","findOnPath_","pathToFollow","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","CompoundWrite","writeTree_","empty","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","newWriteTree","compoundWriteAddWrites","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeRemoveWrite","writeId","allWrites","findIndex","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeRecord","writeTreeRecordContainsPath_","visibleWrites","writeTreeLayerTree_","writeTreeDefaultFilter_","lastWriteId","writes","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","subMerge","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeRefCalcIndexedSlice","completeServerData","toIterate","nodes","writeTreeCalcIndexedSlice","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeRefChild","ChildChangeAccumulator","changeMap","oldChange","oldType","getChanges","NO_COMPLETE_CHILD_SOURCE","getCompleteChild","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","viewProcessorApplyOperation","viewProcessor","oldViewCache","writesCache","completeCache","accumulator","filterServerNode","viewProcessorApplyUserOverwrite","viewProcessorApplyServerOverwrite","changedChildren","curViewCache","viewProcessorCacheHasChild","viewProcessorApplyUserMerge","viewProcessorApplyServerMerge","ackUserWrite","serverChildren","viewProcessorRevertUserWrite","ackPath","mergePath","serverCachePath","viewProcessorAckUserWrite","oldServerNode","viewProcessorGenerateEventCacheAfterServerEvent","viewProcessorListenComplete","isLeafOrEmpty","oldCompleteSnap","viewProcessorMaybeAddValueEvent","changePath","oldEventSnap","completeEventChildren","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","changedSnap","oldServerSnap","newServerCache","serverFilter","newServerNode","viewProcessorApplyMerge","viewMergeTree","childMergeTree","isUnknownDeepMerge","View","initialViewCache","eventRegistrations_","indexFilter","processor_","initialServerCache","initialEventCache","eventGenerator_","viewIsEmpty","viewRemoveEventRegistration","eventRegistration","cancelError","cancelEvents","maybeEvent","createCancelEvent","remaining","hasAnyCallback","concat","viewApplyOperation","viewGenerateEventsForChanges_","referenceConstructor","SyncPoint","views","syncPointApplyOperation","syncPoint","optCompleteServerCache","syncPointGetView","serverCacheComplete","eventCacheComplete","syncPointAddEventRegistration","initialChanges","eventNode","viewGetInitialEvents","syncPointRemoveEventRegistration","removed","hadCompleteView","syncPointHasCompleteView","viewQueryId","_repo","syncPointGetQueryViews","syncPointGetCompleteServerCache","cache","viewGetCompleteServerCache","syncPointViewForQuery","syncPointGetCompleteView","syncPointViewExistsForQuery","syncTreeNextQueryTag_","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","tagToQueryMap","queryToTagMap","syncTreeApplyUserOverwrite","syncTree","syncTreeApplyOperationToSyncPoints_","syncTreeApplyUserMerge","changeTree","syncTreeAckUserWrite","record","writeTreeGetWrite","syncTreeApplyServerOverwrite","syncTreeRemoveEventRegistration","skipListenerDedup","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","maybeChildSyncPoint","childMap","childViews","newQuery","syncTreeCreateListenerForView_","startListening","syncTreeQueryForListening_","syncTreeTagForQuery","stopListening","tagToRemove","syncTreeMakeQueryKey_","queryToRemove","removedQuery","removedQueryKey","removedQueryTag","syncTreeRemoveTags_","syncTreeApplyTaggedQueryOverwrite","queryKey","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryPath","syncTreeApplyTaggedOperation_","syncTreeAddEventRegistration","skipSetupListener","foundAncestorDefaultView","pathToSyncPoint","sp","childSyncPoint","viewAlreadyExists","queriesToStop","childQueries","queryToStop","syncTreeSetupListener_","syncTreeCalcCompleteEventCache","syncTreeGetServerValue","serverCacheNode","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","syncTreeApplyTaggedListenComplete","toUpperCase","errorForServerCode","splitIndex","ExistingValueProvider","DeferredValueProvider","syncTree_","path_","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","unused","existingNode","leaf","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","childCount","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeForEachChild","treeGetPath","childEmpty","childExists","treeIsEmpty","validateFirebaseDataArg","validateFirebaseData","errorPrefixFxn","validateFirebaseMergeDataArg","mergePaths","curPath","isValidPriority","isValidKey","prevPath","validateFirebaseMergePaths","validatePriority","validateKey","validateRootPathString","validatePathString","validateWritablePath","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidPathString","isValidRootPathString","hasDotValue","hasActualChild","last","validateUrl","parsedUrl","EventQueue","eventLists_","recursionDepth_","eventQueueQueueEvents","eventQueue","eventDataList","currList","getPath","eventQueueRaiseEventsAtPath","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventQueueRaiseEventsForChangedPath","changedPath","sentAll","eventList","eventFn","getEventRunner","eventListRaise","INTERRUPT_REASON","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","transactionQueueTree_","persistentConnection_","repoStart","repo","authOverride","search","beingCrawled","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoUpdateInfo","statsReporter_","creatorFunction","infoData_","infoSyncTree_","infoEvents","serverSyncTree_","repoServerTime","offsetNode","repoGenerateServerValues","taggedSnap","taggedChildren","raw","syncTreeApplyTaggedQueryMerge","repoRerunTransactions","repoLog","resolvedOnDisconnectTree","resolved","repoAbortTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoSetWithPriority","newVal","newNodeUnresolved","clearEvents","repoCallOnCompleteCallback","repoOnDisconnectCancel","sparseSnapshotTreeForget","repoOnDisconnectSet","repoRemoveEventCallbackForQuery","repoInterrupt","repoGetLatestState","excludeSets","repoSendReadyTransactions","repoPruneCompletedTransactionsBelowNode","repoBuildTransactionQueue","every","setsToIgnore","txn","currentWriteId","latestState","snapToSend","latestHash","retryCount","currentOutputSnapshotRaw","dataToSend","pathToSend","currentOutputSnapshotResolved","unwatcher","abortReason","repoSendTransactionQueue","rootMostTransactionNode","repoGetAncestorTransactionNode","txnsToRerun","abortTransaction","currentNode","currentInputSnapshot","newDataNode","oldWriteId","newNodeResolved","applyLocally","repoRerunTransactionQueue","transactionNode","transactionQueue","repoAggregateTransactionQueuesForNode","nodeQueue","order","to","includeSelf","treeForEachAncestor","repoAbortTransactionsOnNode","treeForEachDescendant","childrenFirst","lastSent","parseRepoInfo","dataURL","parseDatabaseURL","scheme","subdomain","colonInd","slashInd","questionMarkInd","pathStringDecoded","piece","decodePath","dotInd","queryString","segment","kv","decodeQuery","hostWithoutPort","PUSH_CHARS","nextPushId","lastPushTime","lastRandChars","duplicateTime","timeStampChars","DataEvent","snapshot","ref","getEventType","exportVal","CancelEvent","CallbackContext","snapshotCallback","cancelCallback","onValue","expDataSnapshot","previousChildName","onCancel","hasCancelCallback","userCallback","OnDisconnect","setWithPriority","repoOnDisconnectSetWithPriority","childrenToMerge","repoOnDisconnectUpdate","QueryImpl","_orderByCalled","ReferenceImpl","sameRepo","samePath","sameQueryIdentifier","pathToUrlEncodedString","validateNoPreviousOrderByCall","validateQueryEndpoints","startNode","endNode","tooManyArgsError","wrongArgTypeError","validateLimit","parentPath","DataSnapshot","_node","_index","childRef","exists","hasChildren","_checkNotDeleted","_root","refFromURL","parsedURL","changedKey","changedValue","repoUpdate","callbackContext","ValueEventRegistration","cached","ChildEventRegistration","eventToCheck","cancelCallbackOrListenOptions","onlyOnce","onceCallback","dataSnapshot","repoAddEventCallbackForQuery","onChildAdded","onChildChanged","onChildMoved","onChildRemoved","expCallback","QueryConstraint","QueryEndAtConstraint","_value","_apply","QueryEndBeforeConstraint","queryParamsEndBefore","QueryStartAtConstraint","QueryStartAfterConstraint","queryParamsStartAfter","QueryLimitToFirstConstraint","_limit","newLimit","queryParamsLimitToFirst","QueryLimitToLastConstraint","queryParamsLimitToLast","QueryOrderByChildConstraint","parsedPath","QueryOrderByKeyConstraint","QueryOrderByPriorityConstraint","QueryOrderByValueConstraint","QueryEqualToValueConstraint","queryConstraints","queryImpl","constraint","FIREBASE_DATABASE_EMULATOR_HOST_VAR","repos","useRestClient","repoManagerDatabaseFromApp","dbUrl","databaseURL","isEmulator","dbEmulatorHost","authTokenProvider","appRepos","repoManagerCreateRepo","Database","_repoInternal","_instanceStarted","_rootInternal","repoManagerDeleteRepo","apiName","checkTransportInit","forceWebSockets","forceLongPolling","connectDatabaseEmulator","tokenProvider","mockUserToken","goOnline","enableLoggingImpl","SERVER_TIMESTAMP",".sv","TransactionResult","committed","runTransaction","transactionUpdate","currentState","queueNode","priorityForNode","repoStartTransaction","simpleListen","echo","onEcho","objectToMerge","newObjectToMerge","_database","_validatePathString","getRef","Reference","Query","database","cancelCallbackOrContext","ret","getCancelAndContextArgs_","valueCallback","expSnapshot","validateEventType","once","failureCallbackOrContext","limitToFirst","limit","limitToLast","orderByChild","orderByKey","orderByPriority","orderByValue","startAt","startAfter","endAt","endBefore","equalTo","cancelOrContext","_ReferenceImpl","_QueryImpl","_QueryParams","getParent","getRoot","_validateWritablePath","bool","validateBoolean","transactionResult","setPriority","expPromise","thennablePushRef","pushRef","expRef","ModularOnDisconnect","goOffline","ServerValue","TIMESTAMP","increment","customAuthImpl","_setSDKVersion","_repoManagerDatabaseFromApp","databaseExp","goog","goog.global","aa","goog.isArrayLike","ba","goog.isObject","goog.UID_PROPERTY_","goog.uidCounter_","fa","selfObj","var_args","goog.bindJs_","ha","boundArgs","newArgs","unshift","goog.bind","goog.bind.apply","goog.bindNative_","goog.partial","ia","goog.inherits","childCtor","parentCtor","tempCtor","superClass_","childCtor.base","me","methodName","goog.Disposable","disposed_","onDisposeCallbacks_","dispose","goog.Disposable.prototype.dispose","goog.getUid","disposeInternal","goog.Disposable.MONITORING_MODE","goog.Disposable.prototype.disposeInternal","opt_fromIndex","fromIndex","toArray","rv","extend","arr1","arr2","len1","len2","goog.events.Event","w","opt_target","currentTarget","defaultPrevented","preventDefault","goog.events.Event.prototype.preventDefault","PASSIVE_EVENTS","goog.global.addEventListener","passive","goog.nullFunction","goog.global.removeEventListener","goog.string.internal.isEmptyOrWhitespace","pa","goog.string.internal.trim","trim","ra","getNativeUserAgentString","sa","goog.global.navigator","matchUserAgent","x","goog.reflect.sinkValue","ta","goog.userAgent.VERSION","goog.userAgent.OPERA","goog.userAgent.IE","goog.userAgent.EDGE","goog.userAgent.EDGE_OR_IE","goog.userAgent.GECKO","subString","goog.userAgent.WEBKIT","Ba","docMode","goog.userAgent.getDocumentMode_","Ea","goog.userAgent.isVersionOrHigherCache_","Ia","valueFn","v1Subs","v2Subs","subCount","subIdx","v1Sub","v2Sub","v1Comp","v2Comp","goog.string.internal.compareElements_","cacheObj","goog.userAgent.DOCUMENT_MODE","goog.events.BrowserEvent","z","opt_e","opt_currentTarget","goog.events.Event.call","goog.events.BrowserEvent.base","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","event_","relevantTouch","changedTouches","srcElement","nodeName","MOUSEOVER","fromElement","MOUSEOUT","toElement","pageX","pageY","goog.events.BrowserEvent.IE_POINTER_TYPE_MAP","goog.events.BrowserEvent.superClass_.preventDefault.call","2","TOUCH","3","PEN","4","MOUSE","goog.events.BrowserEvent.prototype.preventDefault","be","returnValue","goog.events.Listenable.IMPLEMENTED_BY_PROP","goog.events.ListenableKey.counter_","goog.events.Listener","Oa","capture","opt_handler","callOnce","goog.events.Listener.prototype.markAsRemoved","opt_obj","clone","Ra","PROTOTYPE_FIELDS","Ta","goog.events.ListenerMap","Ua","typeCount_","Wa","goog.events.ListenerMap.prototype.removeByKey","markAsRemoved","goog.events.ListenerMap.findListenerIndex_","Va","listenerArray","opt_useCapture","opt_listenerScope","listenerObj","goog.events.ListenerMap.prototype.add","typeStr","goog.events.LISTENER_MAP_PROP_","goog.events.onStringMap_","goog.events.listen","opt_options","goog.events.listenOnce","ab","goog.events.wrapListener","listenOnce","goog.events.listen_","listenerMap","goog.events.getListenerMap_","goog.events.getProxy","proxyCallbackFunction","goog.events.handleBrowserEvent_","eventObject","goog.events.BrowserFeature.PASSIVE_EVENTS","goog.events.getOnString_","addListener","removeListener","goog.events.unlistenByKey","ib","removeByKey","eventTargetListeners_","detachEvent","fb","Ya","goog.events.onString_","gb","opt_evt","listenerFn","listenerHandler","goog.events.LISTENER_WRAPPER_PROP_","bb","goog.events.EventTarget","B","goog.Disposable.call","actualEventTarget_","parentEventTarget_","C","goog.events.EventTarget.prototype.dispatchEvent","ancestorsTree","ancestor","getParentEventTarget","oldEvent","opt_ancestorsTree","fireListeners","kb","goog.events.EventTarget.prototype.fireListeners","unlistenByKey","goog.events.EventTarget.prototype.removeEventListener","opt_capture","opt_handlerScope","goog.events.unlisten","goog.events.EventTarget.prototype.disposeInternal","goog.events.EventTarget.superClass_.disposeInternal.call","removeAllListeners","goog.events.EventTarget.prototype.listen","goog.events.EventTarget.prototype.listenOnce","goog.json.serialize","ub","module$contents$goog$async$WorkQueue_WorkQueue.freelist_","create_","reset_","occupants_","head_","item","WorkItem","qb","goog.async.run","sb","opt_context","goog.async.run.schedule_","goog.global.Promise.resolve","goog.async.run.processWorkQueue","wb","goog.async.run.workQueueScheduled_","goog.async.run.workQueue_","workTail_","workHead_","module$contents$goog$async$WorkQueue_WorkQueue.freelist_.get","goog.async.run.workQueue_.remove","throwException","exception","goog.global.setTimeout","module$contents$goog$async$WorkQueue_WorkQueue.freelist_.put","goog.Timer","opt_interval","opt_timerObject","goog.events.EventTarget.call","interval_","timerObject_","boundTick_","tick_","zb","goog.Timer.prototype.stop","timer_","goog.Timer.callOnce","Ab","opt_delay","yb","JSC$2088_enabled","goog.Timer.prototype","JSC$2088_timer_","goog.Timer.prototype.tick_","elapsed","goog.Timer.intervalScale","dispatchTick","goog.Timer.TICK","goog.Timer.prototype.start","goog.Timer.prototype.disposeInternal","goog.Timer.superClass_.disposeInternal.call","Throttle","listener_","args_","shouldFire_","fire","doAction_","Bb","onTimer_","goog.global.clearTimeout","goog.events.EventHandler","D","opt_scope","handler_","keys_","goog.events.EventHandler.typeArray_","Eb","goog.events.EventHandler.prototype.listen_","opt_fn","goog.events.EventHandler.prototype.removeAll","Fb","goog.labs.net.webChannel.WebChannelDebug","Gb","redactEnabled_","WebChannelDebug.prototype.xmlHttpChannelResponseText","E","opt_desc","WebChannelDebug.prototype.redactResponse_","responseArray","dataPart","redactResponse_","goog.events.EventHandler.prototype.disposeInternal","goog.events.EventHandler.superClass_.disposeInternal.call","removeAll","goog.events.EventHandler.prototype.handleEvent","disableRedact","WebChannelDebug.prototype.disableRedact","WebChannelDebug.prototype.info","goog.labs.net.webChannel.requestStats.Event","goog.labs.net.webChannel.requestStats.eventTarget_","Mb","Lb","Nb","goog.labs.net.webChannel.requestStats.Event.SERVER_REACHABILITY_EVENT","SERVER_REACHABILITY_EVENT","requestStats.notifyServerReachabilityEvent","goog.labs.net.webChannel.requestStats.getStatEventTarget_","goog.labs.net.webChannel.requestStats.ServerReachabilityEvent","Ob","goog.labs.net.webChannel.requestStats.Event.STAT_EVENT","STAT_EVENT","requestStats.notifyStatEvent","goog.labs.net.webChannel.requestStats.StatEvent","Pb","goog.labs.net.webChannel.requestStats.Event.TIMING_EVENT","TIMING_EVENT","J","goog.labs.net.webChannel.requestStats.TimingEvent","goog.net.ErrorCode","NO_ERROR","ACCESS_DENIED","FILE_NOT_FOUND","FF_SILENT_ERROR","CUSTOM_ERROR","EXCEPTION","HTTP_ERROR","ABORT","TIMEOUT","OFFLINE","goog.net.EventType","COMPLETE","SUCCESS","READY","READY_STATE_CHANGE","INCREMENTAL_DATA","PROGRESS","DOWNLOAD_PROGRESS","UPLOAD_PROGRESS","goog.net.XmlHttpFactory","Sb","goog.net.XmlHttpFactory.prototype.getOptions","Tb","cachedOptions_","internalGetOptions","goog.net.WebChannel","Ub","goog.net.WebChannel.EventType","OPEN","CLOSE","MESSAGE","goog.net.WebChannel.MessageEvent","Vb","goog.net.WebChannel.MessageEvent.base","goog.net.WebChannel.ErrorEvent","Wb","goog.net.WebChannel.ErrorEvent.base","goog.net.DefaultXmlHttpFactory","Yb","goog.labs.net.webChannel.ChannelRequest","channelDebug","opt_requestId","opt_retryId","channel_","channelDebug_","rid_","retryId_","eventHandler_","timeout_","goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_","pollingTimer_","EDGE_POLLING_INTERVAL_","extraHeaders_","successful_","postData_","requestUri_","baseUri_","type_","requestStartTime_","watchDogTimeoutTime_","watchDogTimerId_","pendingMessages_","xmlHttp_","xmlHttpChunkStart_","lastError_","verb_","lastStatusCode_","cancelled_","readyStateChangeThrottleMs_","readyStateChangeThrottle_","firstByteReceived_","initialResponseDecoded_","decodeInitialResponse_","decodeChunks_","fetchResponseState_","goog.labs.net.webChannel.FetchResponseState","$b","textDecoder","responseBuffer","responseArrivedForFetch","createInstance","goog.net.DefaultXmlHttpFactory.prototype.createInstance","goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions","goog.net.XmlHttp.factory_","goog.labs.net.webChannel.ChannelRequest.INVALID_CHUNK_","goog.labs.net.webChannel.ChannelRequest.INCOMPLETE_CHUNK_","cc","ChannelRequest.prototype.xmlHttpPost","uri","postData","XML_HTTP","makeUnique","decodeChunks","sendXmlHttp_","ChannelRequest.prototype.sendXmlHttp_","ec","hostPrefix","N","ensureWatchDogTimer_","WebChannelDebug.prototype.xmlHttpChannelRequest","verb","attempt","fc","queryData_","useSecondaryDomains","supportsCrossDomainXhrs_","createXhrIo","xmlHttpHandler_","readyStateChangeHandler_","goog.labs.net.webChannel.requestStats.notifyServerReachabilityEvent","keyParts","keyValue","ChannelRequest.prototype.useFetchStreamsForResponse_","jc","CLOSE_REQUEST","usesFetchStreams_","ChannelRequest.prototype.decodeNextChunks_","lc","decodeNextChunksSuccessful","chunkText","sizeEndIndex","sizeStartIndex","ChannelRequest.prototype.getNextChunk_","getNextChunk_","chunkStartIndex","BAD_DATA","goog.labs.net.webChannel.requestStats.notifyStatEvent","REQUEST_INCOMPLETE_DATA","REQUEST_BAD_DATA","safeOnRequestData_","maybeResetBuffer_","NO_DATA","REQUEST_NO_DATA","backChannelRequest_","detectBufferingProxy_","bpDetectionDone_","clearBpDetectionTimer_","NOPROXY","xmlHttpChannelResponseText","cleanup_","dispatchFailure_","ChannelRequest.prototype.ensureWatchDogTimer_","pc","startWatchDogTimer_","ChannelRequest.prototype.startWatchDogTimer_","goog.labs.net.webChannel.requestStats.setTimeout","onWatchDogTimeout_","ChannelRequest.prototype.cancelWatchDogTimer_","ic","Q","ChannelRequest.prototype.dispatchFailure_","CLOSED","onRequestComplete","ChannelRequest.prototype.cleanup_","P","cancelWatchDogTimer_","xmlhttp","ChannelRequest.prototype.safeOnRequestData_","hasRequest","forwardChannelRequestPool_","OPENED","wireCodec_","parser_","ex","responseValues","handlePostResponse_","backChannelTimerId_","goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE","clearDeadBackchannelTimer_","cancelBackChannelRequest_","tc","BACKCHANNEL_MISSING","lastPostResponseArrayId_","lastArrayId_","goog.labs.net.webChannel.WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF","enableStreaming_","backChannelRetryCount_","deadBackChannelTimerId_","onBackChannelDead_","getRequestCount","onForwardChannelFlushed_","forwardChannelFlushedCallback_","signalError_","BAD_RESPONSE","respArray","nextArray","onInput_","OPENING","sid_","hostPrefix_","negotiatedVersion","channelVersion_","negotiatedServerVersion","serverVersion_","httpSessionIdHeader","serverKeepaliveMs","Ca","backChannelRequestTimeoutMs_","applyControlHeaders_","clientProtocol","xhr_","getResponseHeader","goog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL","requestPool_","maxSize_","maxPoolSizeConfigured_","request_","addRequest","getHttpSessionIdParam","httpSessionIdParam_","goog.net.WebChannel.X_HTTP_SESSION_ID","setHttpSessionId","httpSessionId_","setParameterValue","forwardChannelUri_","channelOpened","handshakeRttMs_","startBackchannelAfterHandshake_","backChannelUri_","createDataUri","getBackChannelUri","removeRequest","opt_timeout","ensureBackChannel_","outgoingMaps_","ensureForwardChannel_","STOP","disconnect","channelHandleArray","goog.structs.forEach","Dc","col","goog.structs.getKeys","getKeys","getValues","l","goog.structs.getValues","ChannelRequest.prototype.setTimeout","goog.labs.net.webChannel.ChannelRequest.prototype","ChannelRequest.prototype.readyStateChangeHandler_","evt","throttle","INTERACTIVE","getReadyState","ChannelRequest.prototype.xmlHttpHandler_","onXmlHttpReadyStateChanged_","errorCode","getLastErrorCode","getStatus","getResponseText","useFetchStreamsForResponse_","responseChunks","responseLength","requestCompleted","TextDecoder","goog.global.TextDecoder","stream","WebChannelDebug.prototype.xmlHttpChannelResponseMetaData","goog.net.WebChannel.X_HTTP_INITIAL_RESPONSE","initialResponse","UNKNOWN_SESSION_ID","I","REQUEST_UNKNOWN_SESSION_ID","decodeNextChunks_","listen_","pollResponse_","STATUS","REQUEST_BAD_STATUS","ChannelRequest.prototype.pollResponse_","ChannelRequest.prototype.cancel","ChannelRequest.prototype.onWatchDogTimeout_","WebChannelDebug.prototype.timeoutResponse","handleTimeout_","REQUEST_TIMEOUT","goog.uri.utils.splitRe_","goog.Uri","T","opt_uri","opt_ignoreCase","domain_","userInfo_","scheme_","port_","fragment_","ignoreCase_","Gc","setScheme","setUserInfo","setPort","setPath","goog.Uri.QueryData","encodedQuery_","keyMap_","count_","Jc","setQueryData","SCHEME","goog.Uri.decodeOrEmpty_","USER_INFO","setDomain","DOMAIN","PORT","PATH","QUERY_DATA","setFragment","FRAGMENT","goog.Uri.prototype.clone","M","goog.Uri.prototype.setScheme","newScheme","opt_decode","goog.Uri.prototype.setPort","Hc","newPort","goog.Uri.prototype.setQueryData","queryData","goog.Uri.QueryData.prototype.setIgnoreCase","ignoreCase","ensureKeyMapInitialized_","invalidateCache_","lowerCase","setValues","goog.Uri.encodeSpecialChars_","goog.Uri.reDisallowedInQuery_","goog.Uri.prototype.setParameterValue","S","goog.Uri.prototype.makeUnique","RANDOM","opt_preserveReserved","decodeURI","Lc","unescapedPart","extra","opt_removeDoubleEncoding","encoded","encodeURI","goog.Uri.encodeChar_","Sc","ch","goog.Uri.prototype.toString","getScheme","goog.Uri.reDisallowedInSchemeOrUserInfo_","getDomain","getUserInfo","getPort","hasDomain","goog.Uri.reDisallowedInAbsolutePath_","goog.Uri.reDisallowedInRelativePath_","getEncodedQuery","fragment","getFragment","goog.Uri.reDisallowedInFragment_","Ic","opt_query","goog.Uri.QueryData.prototype.ensureKeyMapInitialized_","U","goog.uri.utils.parseQueryData","encodedQuery","indexOfEquals","Tc","goog.Uri.QueryData.prototype.remove","getKeyName_","goog.Uri.QueryData.prototype.containsKey","Uc","goog.Uri.QueryData.prototype.setValues","goog.Uri.QueryData.prototype.getKeyName_","V","goog.Uri.QueryData.prototype.add","goog.Uri.QueryData.prototype","goog.Uri.QueryData.prototype.forEach","goog.Uri.QueryData.prototype.getKeys","vals","goog.Uri.QueryData.prototype.getValues","opt_key","containsKey","goog.Uri.QueryData.prototype.set","goog.Uri.QueryData.prototype.get","opt_default","goog.Uri.QueryData.prototype.toString","encodedKey","param","goog.labs.net.webChannel.Wire.QueuedMap","mapId","ForwardChannelRequestPool","Wc","opt_maxPoolSize","goog.global.PerformanceNavigationTiming","PerformanceNavigationTiming","entrys","goog.global.performance.getEntriesByType","performance","getEntriesByType","nextHopProtocol","goog.global.chrome","goog.global.chrome.loadTimes","loadTimes","wasFetchedViaSpdy","retValue","Yc","ForwardChannelRequestPool.prototype.isFull","ForwardChannelRequestPool.prototype.getRequestCount","uc","ForwardChannelRequestPool.prototype.hasRequest","ForwardChannelRequestPool.prototype.addRequest","vc","ForwardChannelRequestPool.prototype.removeRequest","ForwardChannelRequestPool.prototype.getPendingMessages","Zc","goog.json.NativeJsonProcessor","goog.labs.net.webChannel.WireV8","netUtils.imageCallback_","dd","img","debugText","onabort","goog.net.FetchXmlHttpFactory","worker_","worker","streamBinaryChunks_","streamBinaryChunks","goog.net.FetchXmlHttp","goog.net.FetchXmlHttp.base","credentialsMode_","goog.net.FetchXmlHttp.RequestState.UNSENT","responseType","statusText","requestHeaders_","responseHeaders_","method_","url_","inProgress_","textDecoder_","currentReader_","fetchResponse_","ForwardChannelRequestPool.prototype.cancel","getPendingMessages","goog.json.NativeJsonProcessor.prototype.stringify","opt_replacer","goog.json.NativeJsonProcessor.prototype.parse","opt_reviver","goog.net.FetchXmlHttpFactory.prototype.createInstance","UNSENT","goog.net.FetchXmlHttp.prototype.readInputFromFetch_","handleDataFromStream_","handleSendFailure_","goog.net.FetchXmlHttp.prototype.requestDone_","DONE","hd","dispatchCallback_","goog.net.FetchXmlHttp.prototype.dispatchCallback_","fd","goog.net.FetchXmlHttp.prototype.open","goog.net.FetchXmlHttp.prototype","goog.net.FetchXmlHttp.prototype.send","opt_data","requestInit","credentials","Request","handleResponse_","goog.net.FetchXmlHttp.prototype.abort","requestDone_","goog.net.FetchXmlHttp.prototype.handleResponse_","HEADER_RECEIVED","LOADING","arrayBuffer","handleResponseArrayBuffer_","ReadableStream","getReader","readInputFromFetch_","text","handleResponseText_","goog.net.FetchXmlHttp.prototype.handleDataFromStream_","dataPacket","newText","goog.net.FetchXmlHttp.prototype.handleResponseText_","goog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_","responseArrayBuffer","goog.net.FetchXmlHttp.prototype.handleSendFailure_","setRequestHeader","goog.net.FetchXmlHttp.prototype.setRequestHeader","goog.net.FetchXmlHttp.prototype.getResponseHeader","getAllResponseHeaders","goog.net.FetchXmlHttp.prototype.getAllResponseHeaders","lines","pair","getCredentialsMode","setCredentialsMode","goog.json.hybrid.parse","goog.net.XhrIo","opt_xmlHttpFactory","goog.net.XhrIo.base","xmlHttpFactory_","active_","xhrOptions_","lastUri_","lastErrorCode_","inAbort_","inOpen_","inSend_","errorDispatched_","timeoutInterval_","timeoutId_","responseType_","goog.net.XhrIo.ResponseType.DEFAULT","useXhr2Timeout_","withCredentials_","DEFAULT","goog.net.XhrIo.HTTP_SCHEME_PATTERN","goog.net.XhrIo.METHODS_WITH_FORM_DATA","od","goog.net.XhrIo.prototype.error_","rd","dispatchErrors_","sd","cleanUpXhr_","goog.net.XhrIo.prototype.dispatchErrors_","td","goog.net.XhrIo.prototype.onReadyStateChangeHelper_","LOCAL_REQUEST_ERROR","onReadyStateChange_","isComplete","isSuccess","OK","CREATED","ACCEPTED","NO_CONTENT","PARTIAL_CONTENT","NOT_MODIFIED","QUIRK_IE_NO_CONTENT","goog.global.self","goog.global.self.location","goog.global.self.location.protocol","goog.net.XhrIo.HTTP_SCHEME_PATTERN.test","LOADED","getStatusText","goog.net.XhrIo.prototype.cleanUpXhr_","opt_fromDispose","cleanUpTimeoutTimer_","clearedOnReadyStateChange","USE_NULL_FUNCTION","goog.net.XhrIo.prototype.cleanUpTimeoutTimer_","goog.net.XhrIo.prototype.getReadyState","O","UNINITIALIZED","hc","goog.net.XhrIo.prototype.getResponse","TEXT","ARRAY_BUFFER","mozResponseArrayBuffer","exports.generateHttpHeadersOverwriteParam","Qa","exports.setHttpHeadersWithOverwriteParam","urlParam","extraHeaders","httpHeaders","module$exports$goog$net$rpc$HttpCors.generateHttpHeadersOverwriteParam","getInternalChannelParam","paramName","defaultValue","internalChannelParams","goog.labs.net.webChannel.WebChannelBase","xd","extraParams_","httpHeadersOverwriteParam_","initHeaders_","nextMapId_","nextRid_","failFast_","$jscomp.scope.getInternalChannelParam","forwardChannelTimerId_","allowStreamingMode_","backChannelAttemptId_","forwardChannelRetryCount_","baseRetryDelayMs_","retryDelaySeedMs_","forwardChannelMaxRetries_","forwardChannelRequestTimeoutMs_","xmlHttpFactory","useFetchStreams","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake_","fastHandshake","encodeInitMessageHeaders_","encodeInitMessageHeaders","blockingHandshake_","blockingHandshake","detectBufferingProxy","nonAckedMapsAtChannelClose_","bpDetectionTimerId_","Ac","WebChannelBase.prototype.disconnect","rid","cancelRequests_","zd","addAdditionalParams_","requestSent","goog.global.navigator.sendBeacon","sendBeacon","goog.global.Image","Image","onClose_","WebChannelBase.prototype.cancelBackChannelRequest_","sc","WebChannelBase.prototype.cancelRequests_","yd","clearForwardChannelTimer_","WebChannelBase.prototype.ensureForwardChannel_","zc","isFull","onStartForwardChannelTimer_","Ed","WebChannelBase.prototype.makeForwardChannelRequest_","opt_retryRequest","module$exports$goog$net$rpc$HttpCors.setHttpHeadersWithOverwriteParam","requeuePendingMaps_","requestText","dequeueOutgoingMaps_","goog.labs.net.webChannel.WebChannelBase.MAX_MAPS_PER_REQUEST_","WebChannelBase.prototype.addAdditionalParams_","WebChannelBase.prototype.dequeueOutgoingMaps_","Dd","maxNum","badMapHandler","badMapError","messageQueue","WireV8.prototype.encodeMessage","buffer","opt_prefix","encodedValue","encodeMessage","pendingMessages","WebChannelBase.prototype.ensureBackChannel_","yc","onStartBackChannelTimer_","WebChannelBase.prototype.maybeRetryBackChannel_","goog.labs.net.webChannel.WebChannelBase.BACK_CHANNEL_MAX_RETRIES","getRetryTime_","oc","WebChannelBase.prototype.clearBpDetectionTimer_","WebChannelBase.prototype.startBackChannel_","Fd","WebChannelBase.prototype.clearDeadBackchannelTimer_","rc","WebChannelBase.prototype.onRequestComplete","mc","WebChannelBase.prototype.maybeRetryForwardChannel_","BACK_CHANNEL","FORWARD_CHANNEL","lastError","maybeRetryForwardChannel_","INIT","getForwardChannelMaxRetries","maybeRetryBackChannel_","REQUEST_FAILED","WebChannelBase.prototype.getRetryTime_","Cd","retryTime","goog.labs.net.webChannel.WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR","WebChannelBase.prototype.signalError_","R","imageUri","testNetworkCallback_","goog.global.location","goog.global.location.protocol","netUtils.testLoadImage","goog.labs.net.webChannel.netUtils.imageCallback_","goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT","cd","ERROR_OTHER","onError_","channelError","Ad","WebChannelBase.prototype.onClose_","channelClosed","WebChannelBase.prototype.createDataUri","wc","locationPage","hostName","opt_scheme","opt_domain","opt_port","getHttpSessionId","WebChannelBase.prototype.createXhrIo","isStreaming","setWithCredentials","WebChannelBase.Handler","Gd","goog.labs.net.webChannel.WebChannelBaseTransport","Hd","X","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.base","messageUrlParams_","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","goog.net.WebChannel.X_CLIENT_PROTOCOL","goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL","initHeaders","initMessageHeaders","messageContentType","goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE","clientProfile","goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE","httpHeadersOverwriteParam","supportsCrossDomainXhr_","sendRawJson_","sendRawJson","httpSessionIdParam","channelHandler_","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.Handler_","WebChannelBaseTransport.Channel.MessageEvent","Id","goog.net.WebChannel.MessageEvent.call","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.MessageEvent.base","__sm__","metadataKey","Jd","goog.net.WebChannel.ErrorEvent.call","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.ErrorEvent.base","NETWORK_ERROR","Y","goog.net.XhrIo.prototype.setWithCredentials","withCredentials","JSC$2188_send","goog.net.XhrIo.prototype.send","opt_method","opt_content","opt_headers","createXhr","goog.net.XmlHttp.factory_.createInstance","goog.net.XmlHttp.factory_.getOptions","error_","content","getPrototypeOf","contentTypeKey","contentIsFormData","FormData","goog.net.XhrIo.CONTENT_TYPE_HEADER","goog.net.XhrIo.FORM_CONTENT_TYPE","y","goog.userAgent.isVersionOrHigher","goog.net.XhrIo.shouldUseXhr2Timeout_","goog.net.XhrIo.prototype","JSC$2188_timeout_","goog.net.XhrIo.prototype.timeout_","goog.net.XhrIo.prototype.abort","opt_failureCode","goog.net.XhrIo.prototype.disposeInternal","goog.net.XhrIo.prototype.disposeInternal.base","goog.net.XhrIo.prototype.onReadyStateChange_","isDisposed","onReadyStateChangeHelper_","onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.getStatus","goog.net.XhrIo.prototype.getResponseText","getResponseJson","goog.net.XhrIo.prototype.getResponseJson","opt_xssiPrefix","kd","goog.net.XhrIo.prototype.getLastErrorCode","JSC$2188_getLastError","goog.net.XhrIo.prototype.getLastError","goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION","goog.labs.net.webChannel.WebChannelBase.prototype","JSC$2195_state_","WebChannelBase.prototype.onStartForwardChannelTimer_","startForwardChannel_","total","goog.labs.net.webChannel.Wire.RAW_DATA_KEY","__data__","goog.labs.net.webChannel.WebChannelBase.MAX_CHARS_PER_GET_","goog.net.WebChannelTransport.CLIENT_VERSION","xmlHttpPost","makeForwardChannelRequest_","WebChannelBase.prototype.onStartBackChannelTimer_","bpDetectionTimeout","startBackChannel_","onBpDetectionTimer_","WebChannelBase.prototype.onBpDetectionTimer_","PROXY","WebChannelBase.prototype.onBackChannelDead_","BACKCHANNEL_DEAD","WebChannelBase.prototype.testNetworkCallback_","networkUp","ERROR_NETWORK","WebChannelBase.Handler.prototype.channelOpened","goog.labs.net.webChannel.WebChannelBase.Handler.prototype","WebChannelBase.Handler.prototype.channelHandleArray","WebChannelBase.Handler.prototype.channelError","WebChannelBase.Handler.prototype.channelClosed","WebChannelBase.Handler.prototype.badMapError","createWebChannel","WebChannelBaseTransport.prototype.createWebChannel","goog.labs.net.webChannel.WebChannelBaseTransport.Channel","WebChannelBaseTransport.Channel.prototype.open","supportCrossDomain","CONNECT_ATTEMPT","channelPath","opt_extraParams","connectChannel_","WebChannelBaseTransport.Channel.prototype.close","WebChannelBaseTransport.Channel.prototype.send","rawJson","messageToMapObject_","WebChannelBaseTransport.Channel.prototype.disposeInternal","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.superClass_.disposeInternal.call","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.disposeInternal.base","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.MessageEvent","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.ErrorEvent","goog.labs.net.webChannel.WebChannelBase.Handler","WebChannelBaseTransport.Channel.Handler_.prototype.channelOpened","WebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray","WebChannelBaseTransport.Channel.Handler_.prototype.channelError","WebChannelBaseTransport.Channel.Handler_.prototype.channelClosed","Qb","Rb","EventType","K","getLastError","us","getStatEventTarget","ErrorCode","module","Event","FetchXmlHttpFactory","WebChannel","XhrIo","isAuthenticated","toKey","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","invalidateToken","enqueueRetryable","shutdown","G","changeListener","g","getAuthHeaderValueForFirstParty","A","Z","tt","nt","nanoseconds","fromMillis","fromDate","toDate","toMillis","_compareTo","st","fromTimestamp","toMicroseconds","toTimestamp","it","segments","construct","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","rt","canonicalString","fromString","emptyPath","ot","ut","isValidIdentifier","isKeyField","keyField","fromServerFormat","ct","fromPath","fromName","collectionGroup","hasCollectionId","getCollectionGroup","getCollectionPath","isDocumentKey","fromSegments","at","indexId","fields","indexState","ht","lt","UNKNOWN_ID","dt","fieldPath","wt","sequenceNumber","yt","mt","gt","readTime","documentKey","largestBatchId","pt","It","Tt","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","Et","At","nextCallback","catchCallback","isDone","callbackAttached","wrapFailure","wrapSuccess","wrapUserFunction","waitFor","or","mapArray","doWhile","Rt","aborted","oncomplete","vt","xt","commit","St","bt","Dt","F","onblocked","$","onversionchange","Pt","cursor","Vt","range","primaryKey","openKeyCursor","openCursor","Ct","Nt","asyncQueue","started","enqueueAfterDelay","kt","localStore","indexManager","getNextCollectionGroupToUpdate","getMinOffsetFromCollectionGroup","localDocuments","getNextDocuments","updateIndexEntries","updateCollectionGroup","batchId","Ot","previousValue","sequenceNumberHandler","writeSequenceNumber","Mt","databaseId","ssl","autoDetectLongPolling","Ft","isDefaultDatabase","$t","Bt","Lt","qt","Ut","Kt","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","Qt","binaryString","fromBase64String","fromUint8Array","Symbol","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","jt","Wt","zt","nanos","Ht","Jt","mapValue","__type__","stringValue","Xt","__local_write_time__","timestampValue","Zt","te","nullValue","ee","we","ne","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","arrayValue","se","ie","oe","ue","ce","ae","he","le","fe","de","ye","inclusive","pe","Ie","Te","field","dir","Ee","Ae","Re","createKeyFieldInFilter","ke","$e","Be","Le","qe","Oe","Me","matchesComparison","isInequality","getFlattenedFilters","getFilters","getFirstInequalityField","filters","Pe","ve","Ve","Se","xe","Ne","Fe","Ue","Ge","je","EMPTY","Qe","isReverse","nodeStack","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","We","first","forEachInRange","forEachWhile","firstAfterOrEqual","ze","unionWith","He","Je","covers","Ye","getFieldsMap","setAll","applyChanges","Ze","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","tn","ft","en","nn","De","sn","Ce","rn","un","NaN","cn","an","explicitOrderBy","limitType","_t","hn","dn","_n","wn","mn","gn","yn","pn","In","Tn","En","An","Rn","bn","Pn","vn","Vn","Sn","Dn","Nn","Bn","kn","On","elements","Mn","qn","Fn","$n","Ln","Un","transform","Gn","transformResults","Qn","updateTime","none","isNone","jn","Wn","zn","is","Zn","Hn","ns","fieldTransforms","precondition","es","Jn","ss","fieldMask","Xn","Kn","getFieldMask","__previous_value__","rs","os","as","hs","cs","ls","mapKeyFn","equalsFn","innerSize","fs","_s","ws","overlayedDocument","ps","Is","Ts","Es","As","bs","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","Ps","createSynthesizedTargetChangeForCurrentChange","resumeToken","current","addedDocuments","modifiedDocuments","removedDocuments","vs","removedTargetIds","Vs","targetId","Ss","targetIds","cause","Ds","Ns","Cs","xs","Gt","forEachTarget","removeTarget","Yt","purpose","getRemoteKeysForTarget","ks","asc","desc","Os","<","<=",">",">=","==","!=","array-contains","in","not-in","array-contains-any","Ms","and","Fs","$s","Bs","Us","Ks","wi","Gs","Qs","Hs","js","Ws","zs","Js","Ys","ti","updateMask","fieldPaths","_i","updateTransforms","setToServerValue","appendMissingElements","removeAllFromArray","currentDocument","ei","si","documents","ii","structuredQuery","collectionId","allDescendants","di","unaryFilter","li","fieldFilter","ai","compositeFilter","hi","direction","before","ri","ui","fi","mi","yi","gi","pi","Ii","Ti","Ei","Ai","Ri","bi","Pi","vi","Vi","Si","Di","Ci","xi","Ni","ki","Oi","Mi","Fi","$i","Bi","Li","qi","Ui","Ki","currentSequenceNumber","Gi","Qi","localWriteTime","baseMutations","mutations","applyToRemoteDocument","mutationResults","applyToLocalView","applyToLocalDocumentSet","mutatedFields","ji","batch","commitVersion","docVersions","Wi","mutation","zi","lastLimboFreeSnapshotVersion","withSequenceNumber","withResumeToken","withLastLimboFreeSnapshotVersion","Hi","Yi","documentId","Xi","noDocument","Zi","unknownDocument","tr","er","localWriteTimeMs","lastListenSequenceNumber","sr","canonicalId","ir","rr","overlayMutation","ur","cr","getBundleMetadata","ar","saveBundleMetadata","getNamedQuery","hr","bundledQuery","saveNamedQuery","lr","userId","getOverlay","fr","getOverlays","saveOverlays","removeOverlaysForBatchId","IDBKeyRange","bound","getOverlaysForCollection","getOverlaysForCollectionGroup","collectionPath","dr","ge","wr","_r","ceil","mr","codePointAt","seed","DataView","setFloat64","gr","yr","pr","Ir","directionalValue","Tr","Er","Ar","Ke","br","Sr","xr","Vr","Dr","Rr","Pr","vr","Cr","Nr","kr","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getMinOffset","Or","Mr","Xe","Fr","Br","Lr","$r","createRange","orderedDocumentKey","only","qr","Ur","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","Kr","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","withCacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","Gr","Qr","DISABLED","jr","referenceDelegate","checkEmpty","zr","addMutationBatch","Hr","lookupMutationBatch","getNextMutationBatchAfterBatchId","getHighestUnacknowledgedBatchId","getAllMutationBatches","getAllMutationBatchesAffectingDocumentKey","getAllMutationBatchesAffectingDocumentKeys","getAllMutationBatchesAffectingQuery","removeMutationBatch","markPotentiallyOrphaned","performConsistencyCheck","Wr","Jr","lastAcknowledgedBatchId","lastStreamToken","Yr","Xr","allocateTargetId","highestTargetId","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","highestListenSequenceNumber","setTargetsMetadata","addTargetData","targetCount","Cn","updateTargetData","removeTargetData","removeMatchingKeysForTargetId","Zr","removeTargets","getTargetCount","getTargetData","addMatchingKeys","eo","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","no","so","xn","maxValue","io","garbageCollector","collectGarbage","ro","calculateTargetCount","nthSequenceNumber","removeOrphanedDocuments","collect","getCacheSize","oo","getTargetCache","uo","getRemoteDocumentCache","newChangeBuffer","getEntry","removeEntry","updateLimboDocument","getSize","co","changesApplied","addEntry","assertNotApplied","getFromCache","getAllFromCache","ao","setIndexManager","_o","updateMetadata","getMetadata","byteSize","wo","go","getAllFromCollection","getAllFromCollectionGroup","mo","lo","trackRemovals","fo","Ji","ho","Yn","yo","po","remoteDocumentCache","mutationQueue","documentOverlayCache","getDocument","getDocuments","getLocalViewOfDocuments","populateOverlays","computeViews","getOverlayedDocuments","recalculateAndSaveOverlays","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingQuery","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","Io","To","overlays","Eo","Ao","ds","Ro","gs","ys","bo","docs","Po","vo","Rs","Vo","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","getBundleCache","So","Do","Ls","Co","autoIncrement","createIndex","unique","xo","deleteObjectStore","No","ko","allowTabSynchronization","clientId","Xs","isPrimary","networkEnabled","Zs","inForeground","ni","oi","ci","enqueueAndForget","Mo","updateTimeMs","Oo","ownerId","leaseTimestampMs","appVersion","enterRestrictedMode","Fo","$o","fromCache","docChanges","Bo","Lo","qo","Uo","removedBatchIds","addedBatchIds","Go","Qo","jo","zo","Ho","Jo","Zo","Yo","Xo","nu","su","iu","ru","ou","uu","activeTargetIds","cu","onlineState","au","hu","syncEngine","onlineStateHandler","getAllActiveQueryTargets","isActiveQueryTarget","addPendingMutation","updateMutationState","addLocalQueryTarget","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","updateQueryState","handleUserChange","setOnlineState","notifyBundleLoaded","storageArea","lu","fu","du","_u","BatchGetDocuments","Commit","RunQuery","RunAggregationQuery","wu","mu","databaseInfo","forwardChannelRequestTimeoutMs","gu","yu","pu","Iu","skipDelay","Tu","authCredentialsProvider","appCheckCredentialsProvider","Ko","Eu","targetChange","targetChangeType","documentChange","documentDelete","documentRemove","Wo","addTarget","goog-listen-tags","labels","Au","streamToken","writeResults","commitTime","tu","eu","Ru","authCredentials","appCheckCredentials","terminate","Pu","vu","datastore","remoteSyncer","Mu","Su","Vu","Du","Ou","ku","xu","Cu","Nu","Fu","qu","Uu","Ku","Qu","ju","Wu","Xu","verifyOperationInProgress","handleCredentialChange","Zu","rejectListen","applyRemoteEvent","rejectFailedWrite","applySuccessfulWrite","nc","targetTimeMs","removalCallback","createAndSchedule","timerHandle","handleDelayElapsed","keyedMap","sortedSet","emptySet","track","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","ac","onListen","bu","dc","onUnlisten","includeMetadataChanges","byteLength","gc","collectionGroups","progress","bytesLoaded","documentsLoaded","namedQuery","documentMetadata","$u","taskState","Bu","Lu","totalDocuments","totalBytes","Gu","zu","Hu","Ju","Yu","Ec","Rc","remoteStore","sharedClientState","maxConcurrentLimboResolutions","isPrimaryClient","Pc","Bc","Vc","ea","xc","Mc","Oc","Fc","$c","qc","synchronizeTabs","gcScheduler","indexBackfillerScheduler","initialUser","cacheSizeBytes","forceOwnership","oa","createDatastore","createRemoteStore","createEventManager","createSyncEngine","ca","la","da","wa","ignoreUndefinedProperties","experimentalForceLongPolling","experimentalAutoDetectLongPolling","ma","_authCredentials","_appCheckCredentials","_databaseId","_persistenceKey","_settings","_settingsFrozen","_initialized","_terminated","_terminateTask","_setSettings","client","sessionIndex","iamToken","authTokenFactory","_getSettings","_freezeSettings","_terminate","ya","converter","firestore","withConverter","_query","Aa","Pa","releaseLock","va","muted","bc","Cc","Nc","xa","readVersions","lastWriteError","writtenDocs","lookup","ensureCommitNotCalled","found","missing","recordVersion","toMutation","preconditionForUpdate","Na","updateFunction","kc","maxAttempts","run","ka","authCredentialListener","appCheckCredentialListener","getConfiguration","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enqueueAndForgetEvenWhileRestricted","onlineComponents","offlineComponents","Ma","Fa","$a","La","qa","Ga","za","Ja","Xa","_completeWith","_updateProgress","_failWith","na","th","Kc","Qc","enqueue","Xc","eh","nh","_progressObserver","_taskCompletionResolver","_lastProgress","onProgress","firestoreFactory","ih","_queue","_firestoreClient","uh","lh","dh","wh","yh","ph","Ih","_byteString","Th","_internalPath","Ah","_methodName","Rh","isFinite","_lat","_long","bh","Ph","vh","Vh","Sh","Hh","Dh","Ch","xh","mergeFields","Qh","Kh","jh","Jh","Nh","_toFieldTransform","kh","Oh","Mh","Uh","Fh","$h","Bh","zh","Lh","qh","Gh","Wh","Yh","_firestore","_userDataWriter","_document","_converter","Xh","fromFirestore","convertValue","Zh","tl","sl","ol","il","_field","_op","_parse","Al","El","Tl","_queryConstraints","_getOperator","_getQueryConstraints","al","_direction","Rl","ll","_limitType","_l","_docOrFields","_inclusive","Il","gl","Pl","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertDocumentKey","vl","toFirestore","Vl","Sl","Dl","_firestoreImpl","Cl","serverTimestamps","xl","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","oldIndex","Nl","kl","Ml","Fl","Ll","Ha","Ul","zl","Kl","jl","Hl","Wl","Xl","Zl","_commitHandler","_mutations","_committed","_dataReader","_verifyNotCommitted","tf","ef","_transaction","nf","validateSetOptions","FirestoreError","assertUint8ArrayAvailable","assertBase64Available","Blob","Bytes","isPartialObserver","IndexedDbPersistenceProvider","enableIndexedDbPersistence","enableMultiTabIndexedDbPersistence","clearIndexedDbPersistence","Firestore","databaseIdOrApp","_persistenceProvider","_DatabaseId","_appCompat","settingsLiteral","currentSettings","_logWarn","connectFirestoreEmulator","enableNetwork","disableNetwork","enablePersistence","experimentalForceOwningTab","_validateIsNotUsedTogether","clearPersistence","waitForPendingWrites","onSnapshotsInSync","CollectionReference","replaceFunctionName","DocumentReference","Transaction","ensureFirestoreConfigured","WriteBatch","ExpWriteBatch","executeWrite","loadBundle","bundleData","expQuery","UserDataWriter","AbstractUserDataWriter","forKey","documentRef","castReference","DocumentSnapshot","ExpDocumentSnapshot","dataOrField","moreFieldsAndValues","FirestoreDataConverter","ExpQueryDocumentSnapshot","QueryDocumentSnapshot","modelObject","converterMapByFirestore","INSTANCES","untypedConverterByConverter","forPath","ExpDocumentReference","_DocumentKey","refEqual","setDoc","fieldOrUpdateData","updateDoc","onSnapshot","extractSnapshotOptions","wrapObserver","getDocFromCache","updated","wrapper","userObserver","snapshotEqual","opStr","directionStr","queryEqual","getDocsFromCache","QuerySnapshot","ExpQuerySnapshot","DocumentChange","docChange","thisArg","docRef","documentPath","addDoc","_cast","firestoreNamespace","GeoPoint","Timestamp","FieldPath","fieldNames","ExpFieldPath","InternalFieldPath","FieldValue","serverTimestamp","delegate","arrayUnion","arrayRemove","firestoreExp","LONG_TYPE","UNSIGNED_LONG_TYPE","mapValues","FUNCTIONS_TYPE","errorCodeMap","FunctionsError","_errorForResponse","bodyJSON","codeForHTTPStatus","description","errorJSON","ContextProvider","messagingProvider","messaging","getAuthToken","getMessagingToken","Notification","permission","getAppCheckToken","messagingToken","DEFAULT_REGION","FunctionsService","regionOrCustomDomain","emulatorOrigin","contextProvider","cancelAllRequests","deleteService","customDomain","region","_url","httpsCallable","functionsInstance","callAtURL","failAfterHandle","millis","failAfter","postJSON","responseData","connectFunctionsEmulator","httpsCallableFromURL","MessageType","_region","_customDomain","_httpsCallable","httpsCallableFromURLExp","useFunctionsEmulator","useFunctionsEmulatorExp","functionsServiceExp","Functions","DEFAULT_SW_PATH","DEFAULT_SW_SCOPE","DEFAULT_VAPID_KEY","ENDPOINT","CONSOLE_CAMPAIGN_ID","CONSOLE_CAMPAIGN_ANALYTICS_ENABLED","arrayToBase64","uint8Array","base64String","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","migrateOldDatabase","senderId","databases","dbNames","tokenDetails","upgradeTransaction","oldDetails","p256dh","fcmToken","subscriptionOptions","swScope","vapidKey","checkTokenDetails","DATABASE_NAME","DATABASE_VERSION","upgradeDb","dbGet","firebaseDependencies","oldTokenDetails","dbSet","only-available-in-window","only-available-in-sw","permission-default","permission-blocked","unsupported-browser","indexed-db-unsupported","failed-service-worker-registration","token-subscribe-failed","token-subscribe-no-token","token-unsubscribe-failed","token-update-failed","token-update-no-token","use-sw-after-get-token","invalid-sw-registration","invalid-bg-handler","invalid-vapid-key","use-vapid-key-after-get-token","requestDeleteToken","unsubscribeOptions","getEndpoint","x-goog-firebase-installations-auth","getBody","web","applicationPubKey","TOKEN_EXPIRATION_MS","pushSubscription","swRegistration","pushManager","getSubscription","userVisibleOnly","applicationServerKey","repeat","rawData","outputArray","base64ToArray","getPushSubscription","dbOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","updatedToken","updateOptions","requestUpdateToken","updatedTokenDetails","deleteTokenInternal","updateToken","getNewToken","dbRemove","subscribeOptions","requestGetToken","externalizePayload","internalPayload","icon","analyticsLabel","collapseKey","collapse_key","messageId","fcmMessageId","messagePayloadInternal","notification","title","image","fcmOptions","click_action","analytics_label","_mergeStrings","s1","s2","resultArray","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","logEvents","isLogServiceStarted","messagingSenderId","registerDefaultSw","browserErrorMessage","requestPermission","ServiceWorkerRegistration","updateSwReg","serviceWorkerRegistration","logToScion","messageType","NOTIFICATION_CLICKED","PUSH_RECEIVED","message_id","message_name","message_time","message_device_time","messageEventListener","dataPayload","isFirebaseMessaging","WindowMessagingFactory","WindowMessagingInternalFactory","deleteToken","_deleteToken","_onMessage","FCM_MSG","SDK_PLATFORM_WEB","EVENT_MESSAGE_DELIVERED","stageLog","fcmEvent","project_number","instance_id","message_type","DISPLAY_NOTIFICATION","DATA_MESSAGE","sdk_platform","package_name","createFcmEvent","event_time_ms","source_extension_json_proto3","createAndEnqueueLogEvent","onPush","getMessagePayloadInternal","clientList","getClientList","sendMessagePayloadInternalToWindows","notificationPayloadInternal","actions","maxActions","showNotification","wrappedInternalPayload","wrapInternalPayload","onNotificationClick","stopImmediatePropagation","isConsoleMessage","getLink","originUrl","clientUrl","getWindowClient","clients","openWindow","matchAll","includeUncontrolled","SwMessagingFactory","waitUntil","newSubscription","onSubChange","onBackgroundMessage","_onBackgroundMessage","MessagingCompatImpl","_getToken","messagingCompatFactory","NAMESPACE_EXPORTS","PushSubscription","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","StorageError","status_","prependCode","_baseMessage","_codeEquals","unknown","retryLimitExceeded","cannotSliceBlob","invalidArgument","appDeleted","invalidRootOperation","invalidFormat","format","Location","bucket","isRoot","fullServerUrl","bucketOnlyServerUrl","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","bucketDomain","gsRegex","httpModify","loc","firebaseStorageHost","firebaseStorageRegExp","cloudStorageHost","groups","regex","indices","postModify","group","captures","bucketValue","pathValue","FailRequest","promise_","getPromise","_appDelete","isString","isNativeBlob","isNativeBlobDefined","validateNumber","argument","minValue","makeUrl","urlPart","makeQueryString","queryPart","nextPart","isRetryStatusCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","isAdditionalRetryCode","NetworkRequest","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","progressCallback_","connectionFactory_","retry","pendingConnection_","backoffId_","canceled_","appDelete_","resolve_","reject_","doTheRequest","backoffCallback","RequestEndStatus","progressListener","progressEvent","loaded","lengthComputable","addUploadProgressListener","removeUploadProgressListener","hitServer","getErrorCode","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","getErrorText","doRequest","backoffCompleteCb","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","responseHandler","clearGlobalTimeout","waitMillis","stopped","wasTimeout","appDelete","getBlob","BlobBuilder","WebKitBlobBuilder","decodeBase64","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","contentType","dataFromString","stringData","utf8Bytes_","base64Bytes_","dataUrl","DataURLParts","percentEncodedBytes_","hasMinus","hasUnder","hasPlus","hasSlash","end","FbsBlob","elideCopy","blobType","data_","size_","startByte","endByte","realBlob","sliced","webkitSlice","mozSlice","blobby","uint8Arrays","finalLength","merged","uploadData","jsonObjectOrNull","lastComponent","lastIndexOf","noXform_","Mapping","server","local","writable","xform","mappings_","getMappings","mappings","nameMapping","_metadata","fullPath","sizeMapping","addRef","_makeStorageReference","fromResourceString","resourceString","resource","mapping","fromResource","toResourceString","PREFIXES_KEY","fromResponseString","listResult","prefixes","items","nextPageToken","pathWithoutTrailingSlash","reference","fromBackendResponse","RequestInfo","errorHandler","progressCallback","successCodes","handlerCheck","cndn","metadataHandler","listHandler","downloadUrlHandler","tokensList","alt","downloadUrlFromResourceString","_protocol","sharedErrorHandler","newErr","objectErrorHandler","shared","maxOperationRetryTime","requestInfo","metadataForUpload_","metadataClone","multipartUpload","X-Goog-Upload-Protocol","boundary","genBoundary","metadata_","preBlobPart","postBlobPart","maxUploadRetryTime","ResumableUploadStatus","checkResumeHeader_","allowed","allowedStatus","createResumableUpload","metadataForUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","continueResumableUpload","bytesLeft","bytesToUpload","uploadCommand","X-Goog-Upload-Offset","uploadStatus","newCurrent","TaskEvent","STATE_CHANGED","TaskState","RUNNING","PAUSED","CANCELED","taskStateFromInternalTaskState","Observer","argsToForward","XhrTextConnection","sent_","initXhr","errorCode_","sendPromise_","upload","newTextConnection","UploadTask","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","completeTransitions_","backoffExpired","isExponentialBackoffExpired","sleepTime","_transition","_metadataErrorHandler","maxSleepTime","_promise","_makeProgressCallback","sizeBefore","_createResumable","_fetchStatus","_fetchMetadata","pendingTimeout","_continueUpload","_oneShotUpload","_resolveToken","_getAuthToken","_getAppCheckToken","_location","createRequest","_makeRequest","statusRequest","uploadRequest","_increaseMultiplier","newStatus","metadataRequest","multipartRequest","transferred","old","_notifyObservers","wasPaused","externalState","bytesTransferred","_addObserver","_removeObserver","onFulfilled","onRejected","_notifyObserver","_finishPromise","triggered","fbsAsync","toCall","valid","pause","_service","_newRef","newPath","_throwIfRoot","listAll","listAllHelper","pageToken","nextPage","list","maxResults","delimiter","requestsList","makeRequestWithTokens","requestsUpdateMetadata","getDownloadURL","requestsGetDownloadUrl","deleteObject","_xhr","_text","requestsDeleteObject","_getChild","canonicalChildPath","refFromPath","FirebaseStorageImpl","_bucket","serviceOrRef","pathOrUrl","extractBucket","_authProvider","_appCheckProvider","_firebaseVersion","_appId","_maxOperationRetryTime","_maxUploadRetryTime","_requests","_overrideAuthToken","tokenData","requestFactory","makeRequest","firebaseVersion","uploadBytesResumable","requestsGetMetadata","getMetadataInternal","refInternal","connectStorageEmulator","connectEmulatorInternal","UploadTaskSnapshotCompat","UploadTaskCompat","wrappedNextOrObserver","taskSnapshot","ListResultCompat","ReferenceCompat","_getChildInternal","putString","_dataFromString","_UploadTask","_FbsBlob","listAllInternal","listInternal","updateMetadataInternal","getDownloadURLInternal","deleteObjectInternal","_invalidRootOperation","StorageServiceCompat","isUrl","_invalidArgument","_Location","setMaxUploadRetryTime","setMaxOperationRetryTime","storageExp","Storage","TRACE_MEASURE_PREFIX","CONFIG_LOCAL_STORAGE_KEY","CONFIG_EXPIRY_LOCAL_STORAGE_KEY","VisibilityState","firebaseInstance","SERVICE_NAME","trace started","trace stopped","nonpositive trace startTime","nonpositive trace duration","no window","no app id","no project id","no api key","invalid cc log","FB not default","RC response not ok","invalid attribute name","invalid attribute value","invalid custom metric name","invalid String merger input","already initialized","consoleLogger","apiInstance","windowInstance","Api","PerformanceObserver","windowLocation","perfMetrics","onFirstInputDelay","getUrl","mark","measure","measureName","mark1","mark2","getEntriesByName","getTimeOrigin","timeOrigin","timing","navigationStart","requiredApisAvailable","setupObserver","entryType","observe","entryTypes","iid","mergeStrings","part1","part2","sizeDiff","settingsServiceInstance","SettingsService","instrumentationEnabled","dataCollectionEnabled","loggingEnabled","tracesSamplingRate","networkRequestsSamplingRate","logEndPointUrl","flTransportEndpointUrl","transportKey","logSource","logTraceAfterSampling","logNetworkAfterSampling","configTimeToLive","getFlTransportFullUrl","RESERVED_ATTRIBUTE_PREFIXES","ATTRIBUTE_FORMAT_REGEX","getVisibilityState","VISIBLE","HIDDEN","getAppId","firebaseApp","REMOTE_CONFIG_SDK_VERSION","DEFAULT_CONFIGS","FIS_AUTH_PREFIX","getConfig","performanceController","expiryString","expiry","configValid","configStringified","getStoredConfig","processConfig","installationsService","authTokenPromise","getAuthTokenPromise","getProjectId","getApiKey","Authorization","app_instance_id","app_instance_id_token","app_id","app_version","sdk_version","COULD_NOT_GET_CONFIG_MSG","storeConfig","fpr_enabled","fpr_log_source","fpr_log_endpoint_url","fpr_log_transport_key","fpr_vc_network_request_sampling_rate","fpr_vc_trace_sampling_rate","shouldLogAfterSampling","samplingRate","initializationStatus","getInitializationPromise","getDocumentReadyComplete","iidPromise","iidVal","getIidPromise","changeInitializationStatus","DEFAULT_SEND_INTERVAL_MS","DEFAULT_REMAINING_TRIES","MAX_EVENT_COUNT_PER_REQUEST","remainingTries","isTransportSetup","processQueue","timeOffset","staged","log_event","eventTime","request_time_ms","client_info","client_type","js_client_info","log_source","flTransportFullUrl","postToFlEndpoint","transportWait","nextRequestWaitMillis","requestOffset","logResponseDetails","responseAction","sendEventsToFl","dispatchQueueEvents","transportHandler","serializer","addToQueue","sendLog","resourceType","logTrace","trace","settingsService","isAuto","sendTraceLog","networkRequestMetric","http_method","httpMethod","http_response_code","response_payload_bytes","responsePayloadBytes","client_start_time_us","startTimeUs","time_to_response_initiated_us","timeToResponseInitiatedUs","time_to_response_completed_us","timeToResponseCompletedUs","perfMetric","application_info","getApplicationInfo","network_request_metric","traceMetric","is_auto","duration_us","durationUs","counters","customAttributes","getAttributes","custom_attributes","trace_metric","serializeTrace","google_app_id","web_app_info","page_url","service_worker_status","visibility_state","effective_connection_type","navigatorConnection","effectiveType","getEffectiveConnectionType","application_process_state","oobMetrics","Trace","traceMeasureName","api","randomId","traceStartMark","traceStopMark","traceMeasure","calculateTraceMetrics","traceName","startTime","duration","metrics","metricName","incrementMetric","numAsInteger","putMetric","customMetricName","valueAsInteger","providedValue","getMetric","putAttribute","attr","isValidName","isValidValue","attributeName","attributeValue","getAttribute","removeAttribute","setStartTime","setDuration","perfMeasureEntries","perfMeasureEntry","createOobTrace","navigationTimings","paintTimings","firstInputDelay","route","timeOriginUs","domInteractive","domContentLoadedEventEnd","loadEventEnd","firstPaint","paintObject","firstContentfulPaint","createUserTimingTrace","createNetworkRequestEntry","performanceEntry","responseStart","responseEnd","networkRequest","networkRequestUrl","logEndpointUrl","flEndpointUrl","logNetworkRequest","transferSize","FID_WAIT_TIME_MS","setupOobResources","setupOobTraces","resources","setupNetworkRequests","measures","setupUserTimingTraces","PerformanceController","_init","perfInstance","PerformanceCompatImpl","performanceFactory","RemoteConfigAbortSignal","registration-window","registration-project-id","registration-api-key","registration-app-id","storage-delete","fetch-client-network","fetch-timeout","fetch-client-parse","fetch-status","indexed-db-unavailable","BOOLEAN_TRUTHY_VALUES","Value","_source","asString","asBoolean","asNumber","getSource","remoteConfig","lastSuccessfulFetchResponse","activeConfigEtag","getLastSuccessfulFetchResponse","getActiveConfigEtag","eTag","_storageCache","setActiveConfig","setActiveConfigEtag","ensureInitialized","_initializePromise","loadFromStorage","_isInitializationComplete","fetchConfig","abortSignal","fetchTimeoutMillis","_client","cacheMaxAgeMillis","minimumFetchIntervalMillis","setLastFetchStatus","lastFetchStatus","getAllKeys","obj1","obj2","getActiveConfig","defaultConfig","allConfigs","_logger","activeConfig","ValueImpl","CachingClient","storageCache","isCachedDataFresh","lastSuccessfulFetchTimestampMillis","cacheAgeMillis","getLastSuccessfulFetchTimestampMillis","storageOperations","setLastSuccessfulFetchTimestampMillis","setLastSuccessfulFetchResponse","RestClient","firebaseInstallations","installationId","installationToken","FIREBASE_REMOTE_CONFIG_URL_BASE","Content-Encoding","If-None-Match","requestBody","language_code","fetchPromise","timeoutPromise","responseEtag","RetryingClient","attemptFetch","RemoteConfig","fetchTimeMillis","getLastFetchStatus","toFirebaseError","APP_NAMESPACE_STORE","openDbPromise","openDatabase","etag","createCompositeKey","StorageCache","lastFetchStatusPromise","lastSuccessfulFetchTimestampMillisPromise","activeConfigPromise","timestampMillis","FirebaseLogLevel","restClient","retryingClient","cachingClient","remoteConfigInstance","RemoteConfigImpl","RemoteConfigCompatImpl","fetchAndActivate","getBoolean","getNumber","getString","remoteConfigFactory"],"mappings":"wOAkV4B,SAAfA,EAAyBC,GACpC,IAAMC,EAAYC,EAAkBF,GACpC,OAAOG,EAAOC,gBAAgBH,GAAW,GC/T9B,MAAAI,EAAY,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IFC,uBACE,wEACFC,8BACE,4FACFC,gBAA+B,wCAC/BC,0BACE,qEACFC,kBACE,sEACFC,oBACE,kDACFC,qBACE,4DACFC,0BACE,+KAEFC,+BACE,iFACFC,yBACE,uGAEFC,0BACE,0FAEFC,sBACE,+IAEFC,sBACE,2GAEFC,iBACE,gEACFC,2BACE,oFACFC,uBACE,gPAIFC,sBACE,wCACFC,0BACE,4GAEFC,iBACE,6KAEFC,0BACE,2EACFC,oBACE,4CACFC,gBACE,4DACFC,2BACE,2FACFC,8BACE,8HAEFC,yBACE,gIAEFC,4BACE,6EACFC,uBACE,kDACFC,uBAAsC,sCACtCC,wBACE,oEACFC,2BACE,oKAGFC,4BACE,2CACFC,+BACE,mEACFC,uBACE,wEACFC,0BACE,uEACFtoB,cACE,iDACFuoB,8BACE,2EACFC,6BACE,yEACFC,2CACE,wJAGFC,yBACE,kGACFC,gBAA+B,sCAC/BC,mBACE,6DACFC,YACE,0GAEFC,wBACE,yJAGFC,8CACE,kLAGFC,gBACE,4FACFC,uBACE,yEACFC,0BACE,kEACFC,iBACE,4DACFC,6BACE,2EACFC,6BACE,mDACFC,sBACE,6DACFC,+BACE,yDACFC,uCACE,4EACFC,qBACE,sEACFlW,QAAyB,+BACzBmW,qBACE,yEACFC,oBACE,0FAEFC,4BACE,2GAEFC,2BACE,sHACFC,+BACE,2EACFC,+BACE,6DACFC,mBACE,2CACFC,iBACE,wEACFC,iBACE,4FAEFC,gBACE,0DACFC,gBACE,+EACFC,kBAAiC,GACjCC,gBACE,kDACFC,0BACE,+EACFpZ,sBACE,qOA8BC,MASMqZ,GAA6B/F,GAuD7BgG,GAA8B,IAAIpgC,EAG7C,OAAQ,WAAYo6B,MC9ahBiG,GAAY,IAAIvyB,GAAO,kBAiBb,SAAAwyB,GAAUC,KAAgB7yB,GACpC2yB,GAAU1yB,UAAYlS,EAAS0R,OACjCkzB,GAAU9mC,eAAe3D,QAAiB2qC,OAAU7yB,GCmBxC,SAAA8yB,GACdC,KACGC,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