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BAAqB,IAG1B1B,EAAS2B,mDACX,CAEAkpF,CAAgB1rF,EAAAA","sources":["webpack://app/../src/platform.ts","webpack://app/../src/persistence.ts","webpack://app/../src/popup_redirect.ts","webpack://app/../src/wrap.ts","webpack://app/../src/user_credential.ts","webpack://app/../src/user.ts","webpack://app/../src/auth.ts","webpack://app/../src/phone_auth_provider.ts","webpack://app/../src/recaptcha_verifier.ts","webpack://app/../index.ts","webpack://app/../src/core/version.ts","webpack://app/../src/core/storage/DOMStorageWrapper.ts","webpack://app/../src/core/storage/MemoryStorage.ts","webpack://app/../src/core/storage/storage.ts","webpack://app/../src/core/util/util.ts","webpack://app/../src/core/AppCheckTokenProvider.ts","webpack://app/../src/core/AuthTokenProvider.ts","webpack://app/../src/realtime/Constants.ts","webpack://app/../src/core/RepoInfo.ts","webpack://app/../src/core/stats/StatsCollection.ts","webpack://app/../src/core/stats/StatsManager.ts","webpack://app/../src/realtime/polling/PacketReceiver.ts","webpack://app/../src/realtime/BrowserPollConnection.ts","webpack://app/../src/realtime/WebSocketConnection.ts","webpack://app/../src/realtime/TransportManager.ts","webpack://app/../src/realtime/Connection.ts","webpack://app/../src/core/ServerActions.ts","webpack://app/../src/core/util/EventEmitter.ts","webpack://app/../src/core/util/OnlineMonitor.ts","webpack://app/../src/core/util/Path.ts","webpack://app/../src/core/util/VisibilityMonitor.ts","webpack://app/../src/core/PersistentConnection.ts","webpack://app/../src/core/snap/Node.ts","webpack://app/../src/core/snap/indexes/Index.ts","webpack://app/../src/core/snap/indexes/KeyIndex.ts","webpack://app/../src/core/util/SortedMap.ts","webpack://app/../src/core/snap/comparators.ts","webpack://app/../src/core/snap/snap.ts","webpack://app/../src/core/snap/LeafNode.ts","webpack://app/../src/core/snap/indexes/PriorityIndex.ts","webpack://app/../src/core/snap/childSet.ts","webpack://app/../src/core/snap/IndexMap.ts","webpack://app/../src/core/snap/ChildrenNode.ts","webpack://app/../src/core/snap/nodeFromJSON.ts","webpack://app/../src/core/snap/indexes/PathIndex.ts","webpack://app/../src/core/snap/indexes/ValueIndex.ts","webpack://app/../src/core/view/Change.ts","webpack://app/../src/core/view/filter/IndexedFilter.ts","webpack://app/../src/core/view/filter/RangedFilter.ts","webpack://app/../src/core/view/filter/LimitedFilter.ts","webpack://app/../src/core/view/QueryParams.ts","webpack://app/../src/core/ReadonlyRestClient.ts","webpack://app/../src/core/SnapshotHolder.ts","webpack://app/../src/core/SparseSnapshotTree.ts","webpack://app/../src/core/stats/StatsListener.ts","webpack://app/../src/core/stats/StatsReporter.ts","webpack://app/../src/core/operation/Operation.ts","webpack://app/../src/core/operation/AckUserWrite.ts","webpack://app/../src/core/operation/ListenComplete.ts","webpack://app/../src/core/operation/Overwrite.ts","webpack://app/../src/core/operation/Merge.ts","webpack://app/../src/core/view/CacheNode.ts","webpack://app/../src/core/view/EventGenerator.ts","webpack://app/../src/core/view/ViewCache.ts","webpack://app/../src/core/util/ImmutableTree.ts","webpack://app/../src/core/CompoundWrite.ts","webpack://app/../src/core/WriteTree.ts","webpack://app/../src/core/view/ChildChangeAccumulator.ts","webpack://app/../src/core/view/CompleteChildSource.ts","webpack://app/../src/core/view/ViewProcessor.ts","webpack://app/../src/core/view/View.ts","webpack://app/../src/core/SyncPoint.ts","webpack://app/../src/core/SyncTree.ts","webpack://app/../src/core/util/ServerValues.ts","webpack://app/../src/core/util/Tree.ts","webpack://app/../src/core/util/validation.ts","webpack://app/../src/core/view/EventQueue.ts","webpack://app/../src/core/Repo.ts","webpack://app/../src/core/util/libs/parser.ts","webpack://app/../src/core/util/NextPushId.ts","webpack://app/../src/core/view/Event.ts","webpack://app/../src/core/view/EventRegistration.ts","webpack://app/../src/api/OnDisconnect.ts","webpack://app/../src/api/Reference_impl.ts","webpack://app/../src/api/Database.ts","webpack://app/../src/api/ServerValue.ts","webpack://app/../src/api/Transaction.ts","webpack://app/../src/api/test_access.ts","webpack://app/../src/register.ts","webpack://app/../src/util/util.ts","webpack://app/../src/api/onDisconnect.ts","webpack://app/../src/api/TransactionResult.ts","webpack://app/../src/api/Reference.ts","webpack://app/../src/util/validation.ts","webpack://app/../src/api/internal.ts","webpack://app/../src/index.ts","webpack://app/../src/implementation/constants.ts","webpack://app/../src/implementation/error.ts","webpack://app/../src/implementation/connection.ts","webpack://app/../src/implementation/location.ts","webpack://app/../src/implementation/failrequest.ts","webpack://app/../src/implementation/type.ts","webpack://app/../src/implementation/url.ts","webpack://app/../src/implementation/utils.ts","webpack://app/../src/implementation/request.ts","webpack://app/../src/implementation/backoff.ts","webpack://app/../src/implementation/fs.ts","webpack://app/../src/platform/browser/base64.ts","webpack://app/../src/implementation/string.ts","webpack://app/../src/implementation/blob.ts","webpack://app/../src/implementation/json.ts","webpack://app/../src/implementation/path.ts","webpack://app/../src/implementation/metadata.ts","webpack://app/../src/implementation/list.ts","webpack://app/../src/implementation/requestinfo.ts","webpack://app/../src/implementation/requests.ts","webpack://app/../src/implementation/taskenums.ts","webpack://app/../src/implementation/observer.ts","webpack://app/../src/implementation/async.ts","webpack://app/../src/platform/browser/connection.ts","webpack://app/../src/task.ts","webpack://app/../src/reference.ts","webpack://app/../src/service.ts","webpack://app/../src/constants.ts","webpack://app/../src/api.ts","webpack://app/../src/assert.ts","webpack://app/../src/crypt.ts","webpack://app/../src/deepCopy.ts","webpack://app/../src/global.ts","webpack://app/../src/defaults.ts","webpack://app/../src/deferred.ts","webpack://app/../src/emulator.ts","webpack://app/../src/environment.ts","webpack://app/../src/errors.ts","webpack://app/../src/json.ts","webpack://app/../src/jwt.ts","webpack://app/../src/obj.ts","webpack://app/../src/query.ts","webpack://app/../src/sha1.ts","webpack://app/../src/subscribe.ts","webpack://app/../src/validation.ts","webpack://app/../src/utf8.ts","webpack://app/../src/uuid.ts","webpack://app/../src/exponential_backoff.ts","webpack://app/../src/compat.ts","webpack://app/../../src/state.ts","webpack://app/../../src/constants.ts","webpack://app/../../src/proactive-refresh.ts","webpack://app/../../src/errors.ts","webpack://app/../../src/util.ts","webpack://app/../../src/client.ts","webpack://app/../../src/indexeddb.ts","webpack://app/../../src/logger.ts","webpack://app/../../src/storage.ts","webpack://app/../../src/debug.ts","webpack://app/../../src/internal-api.ts","webpack://app/../../src/factory.ts","webpack://app/../../src/recaptcha.ts","webpack://app/../../src/providers.ts","webpack://app/../../src/api.ts","webpack://app/../../src/index.ts","webpack://app/../../src/service.ts","webpack://app/../../src/firebaseApp.ts","webpack://app/../../src/firebaseNamespace.ts","webpack://app/../../src/firebaseNamespaceCore.ts","webpack://app/../../src/registerCoreComponents.ts","webpack://app/../../src/platformLoggerService.ts","webpack://app/../../src/internal.ts","webpack://app/../../src/heartbeatService.ts","webpack://app/../../src/component.ts","webpack://app/../../src/provider.ts","webpack://app/../../src/component_container.ts","webpack://app/../../src/tasksnapshot.ts","webpack://app/../../src/task.ts","webpack://app/../../src/list.ts","webpack://app/../../src/reference.ts"],"sourcesContent":["/**\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 {\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 {\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._getRedirectResult;\n _overrideRedirectResult = exp._overrideRedirectResult;\n\n async _initialize(auth: exp.AuthImpl): Promise {\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 {\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 {\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 {\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 {\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 {\n unwrap(): T;\n}\n\n/** Reverse direction wrapper from Exp --wrapped--> Compat */\nexport interface ReverseWrapper {\n wrapped(): T;\n}\n\nexport function unwrap(object: unknown): T {\n return (object as Wrapper).unwrap();\n}\n\nexport function wrapped(object: unknown): T {\n return (object as ReverseWrapper).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;\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\n): Promise {\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\n): Promise {\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 {\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 {\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();\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 {\n return this._delegate.delete();\n }\n reload(): Promise {\n return this._delegate.reload();\n }\n toJSON(): object {\n return this._delegate.toJSON();\n }\n getIdTokenResult(forceRefresh?: boolean): Promise {\n return this._delegate.getIdTokenResult(forceRefresh);\n }\n getIdToken(forceRefresh?: boolean): Promise {\n return this._delegate.getIdToken(forceRefresh);\n }\n linkAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise {\n return this.linkWithCredential(credential);\n }\n async linkWithCredential(\n credential: compat.AuthCredential\n ): Promise {\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 {\n return convertConfirmationResult(\n this.auth,\n exp.linkWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier)\n );\n }\n async linkWithPopup(\n provider: compat.AuthProvider\n ): Promise {\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 {\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 {\n return this.reauthenticateWithCredential(credential);\n }\n async reauthenticateWithCredential(\n credential: compat.AuthCredential\n ): Promise {\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 {\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 {\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 {\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 {\n return exp.sendEmailVerification(this._delegate, actionCodeSettings);\n }\n async unlink(providerId: string): Promise {\n await exp.unlink(this._delegate, providerId);\n return this;\n }\n updateEmail(newEmail: string): Promise {\n return exp.updateEmail(this._delegate, newEmail);\n }\n updatePassword(newPassword: string): Promise {\n return exp.updatePassword(this._delegate, newPassword);\n }\n updatePhoneNumber(phoneCredential: compat.AuthCredential): Promise {\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 {\n return exp.updateProfile(this._delegate, profile);\n }\n verifyBeforeUpdateEmail(\n newEmail: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise {\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 {\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, _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 {\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 {\n return exp.applyActionCode(this._delegate, code);\n }\n\n checkActionCode(code: string): Promise {\n return exp.checkActionCode(this._delegate, code);\n }\n\n confirmPasswordReset(code: string, newPassword: string): Promise {\n return exp.confirmPasswordReset(this._delegate, code, newPassword);\n }\n\n async createUserWithEmailAndPassword(\n email: string,\n password: string\n ): Promise {\n return convertCredential(\n this._delegate,\n exp.createUserWithEmailAndPassword(this._delegate, email, password)\n );\n }\n fetchProvidersForEmail(email: string): Promise {\n return this.fetchSignInMethodsForEmail(email);\n }\n fetchSignInMethodsForEmail(email: string): Promise {\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 {\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 | ((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 | ((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 {\n return exp.sendSignInLinkToEmail(this._delegate, email, actionCodeSettings);\n }\n sendPasswordResetEmail(\n email: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise {\n return exp.sendPasswordResetEmail(\n this._delegate,\n email,\n actionCodeSettings || undefined\n );\n }\n async setPersistence(persistence: string): Promise {\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.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 {\n return this.signInWithCredential(credential);\n }\n signInAnonymously(): Promise {\n return convertCredential(\n this._delegate,\n exp.signInAnonymously(this._delegate)\n );\n }\n signInWithCredential(\n credential: compat.AuthCredential\n ): Promise {\n return convertCredential(\n this._delegate,\n exp.signInWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n signInWithCustomToken(token: string): Promise {\n return convertCredential(\n this._delegate,\n exp.signInWithCustomToken(this._delegate, token)\n );\n }\n signInWithEmailAndPassword(\n email: string,\n password: string\n ): Promise {\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 {\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 {\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 {\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 {\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 {\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 {\n return exp.verifyPasswordResetCode(this._delegate, code);\n }\n unwrap(): exp.Auth {\n return this._delegate;\n }\n _delete(): Promise {\n return this._delegate._delete();\n }\n private linkUnderlyingAuth(): void {\n (this._delegate as unknown as ReverseWrapper).wrapped = () => this;\n }\n}\n\nfunction wrapObservers(\n nextOrObserver: Observer | ((a: compat.User | null) => unknown),\n error?: (error: compat.Error) => unknown,\n complete?: Unsubscribe\n): Partial> {\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 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\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 {\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\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 {\n return this._delegate.render();\n }\n verify(): Promise {\n return this._delegate.verify();\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 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 { 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\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 {\n if (!this.appCheck) {\n return new Promise((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;\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\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 {\n if (!this.auth_) {\n return new Promise((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 {\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 public readonly isUsingEmulator: 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(\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();\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 = '';\n }\n const iframeContents = '' + script + '';\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////\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 const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\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. .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;\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\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 {\n this.initConnection_();\n\n const deferred = new Deferred();\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 {\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 = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n private nodeStack_: Array | LLRBEmptyNode> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\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;\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 {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\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 | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\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 | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\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 {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).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): LLRBNode {\n let n: LLRBNode = 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 | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = 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).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\n ): LLRBNode | LLRBEmptyNode {\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;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).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 {\n let n: LLRBNode = 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 {\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).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 {\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 {\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;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\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;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\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 {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\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 | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\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): LLRBNode {\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): LLRBEmptyNode {\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 {\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,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\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 {\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 {\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(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\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, 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 { 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 { 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 { 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 (\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode | 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 {\n let node: LLRBNode = 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) {\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(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 | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap | 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\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\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, 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\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap) => {\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,\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(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,\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 {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\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 {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\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 | 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(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;\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 {\n const qs: Record = {};\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 {\n const obj: Record = {};\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 {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred();\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;\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 { 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 { 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,\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\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>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = new ImmutableTree(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\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 {\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(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 {\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(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 {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(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(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): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(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(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_(\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) => {\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(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_(\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 {\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 {\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(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) => {\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) {}\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 not 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(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,\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 = 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,\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\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,\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;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree(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,\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(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(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 { 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 = 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 = new ImmutableTree(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 = new Map();\n readonly queryToTagMap: Map = 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(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 ->\n * 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,\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,\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\n): View[] {\n return subtree.fold((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(\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 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 {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record>;\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 {\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 | null = null,\n public node: TreeNode = { 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(tree: Tree, pathObj: string | Path): Tree {\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(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(tree: Tree): 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(tree: Tree, 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(tree: Tree): 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(tree: Tree): 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(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode) => {\n action(new Tree(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(\n tree: Tree,\n action: (tree: Tree) => 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(\n tree: Tree,\n action: (tree: Tree) => 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(\n tree: Tree,\n action: (tree: Tree) => 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(tree: Tree) {\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(tree: Tree) {\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(tree: Tree, childName: string, child: Tree) {\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();\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 {\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 = 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 {\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\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,\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\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) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree) => {\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\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 .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://.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 {\n const deferred = new Deferred();\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 {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\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 {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\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 {\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();\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 {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record,\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, '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 = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise;\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 {\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 {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\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 {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\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 {\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();\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 {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record,\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 {\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(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(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(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(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(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(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(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(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(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(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(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(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 /*isUsingEmulator=*/ true\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,\n appCheckProvider?: Provider,\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 {\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 *

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 {\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();\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// 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 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 {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise {\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 {\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 {\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 {\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,\n onComplete?: (a: Error | null) => void\n ): Promise {\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 {\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 {\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 {\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 {\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();\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 {\n then: Promise['then'];\n catch: Promise['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 {\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 {\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 {\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 {\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 {\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 {\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\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({\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(\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 * Firebase Realtime Database\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 { Database } from './api/Database';\nimport { registerDatabase } from './register';\n\nexport * from './api';\n\nregisterDatabase();\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'database': Database;\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 unique to the `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` objects.\n */\nexport 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/** Network headers */\nexport type Headers = Record;\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 {\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;\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 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 implements Request {\n promise_: Promise;\n\n constructor(error: StorageError) {\n this.promise_ = Promise.reject(error);\n }\n\n /** @inheritDoc */\n getPromise(): Promise {\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(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 {\n getPromise(): Promise;\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 implements Request {\n private pendingConnection_: Connection | null = null;\n private backoffId_: backoffId | null = null;\n private resolve_!: (value?: O | PromiseLike) => 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;\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,\n private errorCallback_: ErrorHandler | null,\n private timeout_: number,\n private progressCallback_: ((p1: number, p2: number) => void) | null,\n private connectionFactory_: () => Connection,\n private retry = true\n ) {\n this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve as (value?: O | PromiseLike) => 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\n ) => void = (requestWentThrough, status) => {\n const resolve = this.resolve_;\n const reject = this.reject_;\n const connection = status.connection as Connection;\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 {\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 {\n /**\n * True if the request was canceled.\n */\n canceled: boolean;\n\n constructor(\n public wasSuccessCode: boolean,\n public connection: Connection | 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(\n requestInfo: RequestInfo,\n appId: string | null,\n authToken: string | null,\n appCheckToken: string | null,\n requestFactory: () => Connection,\n firebaseVersion?: string,\n retry = true\n): Request {\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(\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): 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:[][;base64],\"\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): FbsBlob | null {\n if (isNativeBlobDefined()) {\n const blobby: Array = 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_(metadata: Metadata, value: T): T {\n return value;\n}\n\nclass Mapping {\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>;\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('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('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('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('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('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).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,\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 = (\n connection: Connection,\n response: I\n) => O;\n\n/** A function to handle an error. */\nexport type ErrorHandler = (\n connection: Connection,\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 {\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,\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, p2: string) => Metadata {\n function handler(xhr: Connection, 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, p2: string) => ListResult {\n function handler(xhr: Connection, 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, p2: string) => string | null {\n function handler(xhr: Connection, 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, p2: StorageError) => StorageError {\n function errorHandler(\n xhr: Connection,\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, p2: StorageError) => StorageError {\n const shared = sharedErrorHandler(location);\n\n function errorHandler(\n xhr: Connection,\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 {\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 {\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(\n service: FirebaseStorageImpl,\n location: Location,\n maxDownloadSizeBytes?: number\n): RequestInfo {\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, 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 {\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,\n mappings: Mappings\n): RequestInfo {\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 {\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, _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 {\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,\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 {\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 {\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 {\n const headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: Connection): 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 {\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,\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 *

    \n *
  • The `next` function is triggered on progress updates and when the\n * task is paused/resumed with an `UploadTaskSnapshot` as the first\n * argument.
  • \n *
  • The `error` function is triggered if the upload is canceled or fails\n * for another reason.
  • \n *
  • The `complete` function is triggered if the upload completes\n * successfully.
  • \n *
\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 = (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 {\n /**\n * Function that is called once for each value in the event stream.\n */\n next?: NextFn;\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 = (\n next?: NextFn | StorageObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\nexport class Observer implements StorageObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n\n constructor(\n nextOrObserver?: NextFn | StorageObserver,\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;\n this.error = error ?? undefined;\n this.complete = complete ?? undefined;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn;\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) | 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\n implements Connection\n{\n protected xhr_: XMLHttpRequest;\n private errorCode_: ErrorCode;\n private sendPromise_: Promise;\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 {\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 {\n initXhr(): void {\n this.xhr_.responseType = 'text';\n }\n}\n\nexport function newTextConnection(): Connection {\n return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\n}\n\nexport class XhrBytesConnection extends XhrConnection {\n private data_?: ArrayBuffer;\n\n initXhr(): void {\n this.xhr_.responseType = 'arraybuffer';\n }\n}\n\nexport function newBytesConnection(): Connection {\n return new XhrBytesConnection();\n}\n\nexport class XhrBlobConnection extends XhrConnection {\n initXhr(): void {\n this.xhr_.responseType = 'blob';\n }\n}\n\nexport function newBlobConnection(): Connection {\n return new XhrBlobConnection();\n}\n\nexport function newStreamConnection(): Connection {\n throw new Error('Streams are only supported on Node');\n}\n\nexport function injectTestConnection(\n factory: (() => Connection) | 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> = [];\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 = 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;\n private _promise: Promise;\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\n | null\n | ((snapshot: UploadTaskSnapshot) => unknown),\n error?: ((a: StorageError) => unknown) | null,\n completed?: CompleteFn | null\n ): Unsubscribe | Subscribe {\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\n | NextFn) || 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(\n onFulfilled?: ((value: UploadTaskSnapshot) => U | Promise) | null,\n onRejected?: ((error: StorageError) => U | Promise) | null\n ): Promise {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this._promise.then(\n onFulfilled as (value: UploadTaskSnapshot) => U | Promise,\n onRejected as ((error: unknown) => Promise) | null\n );\n }\n\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n catch(onRejected: (p1: StorageError) => T | Promise): Promise {\n return this.then(null, onRejected);\n }\n\n /**\n * Adds the given observer.\n */\n private _addObserver(observer: Observer): void {\n this._observers.push(observer);\n this._notifyObserver(observer);\n }\n\n /**\n * Removes the given observer.\n */\n private _removeObserver(observer: Observer): 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): 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:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\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:///\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 {\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 {\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 {\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 {\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 {\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 {\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 {\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 {\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\n): Promise {\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 {\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 {\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>;\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,\n /**\n * @internal\n */\n readonly _appCheckProvider: Provider,\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 {\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 {\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 {\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(\n requestInfo: RequestInfo,\n requestFactory: () => Connection,\n authToken: string | null,\n appCheckToken: string | null,\n retry = true\n ): Request {\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(\n requestInfo: RequestInfo,\n requestFactory: () => Connection\n ): Promise {\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 */\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 */\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\nexport { StorageError, StorageErrorCode } from './implementation/error';\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 {\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 {\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 {\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 {\n ref = getModularInstance(ref);\n return getMetadataInternal(ref as Reference) as Promise;\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 {\n ref = getModularInstance(ref);\n return updateMetadataInternal(\n ref as Reference,\n metadata as Partial\n ) as Promise;\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 {\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 {\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 {\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 {\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 * @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\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 new DecodeBase64StringError();\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 * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\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 * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy(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)[prop] = deepExtend(\n (target as Record)[prop],\n (source as Record)[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;\n emulatorHosts?: Record;\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 | 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 = (\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 class Deferred {\n promise: Promise;\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;\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 {\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 = {\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('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 = {\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\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\n ) {}\n\n create(\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(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet(\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(\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)[k];\n const bProp = (b as Record)[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 {\n const obj: Record = {};\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 = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer {\n // Called once for each value in a stream of values.\n next: NextFn;\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 = Partial>;\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 {\n (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver): Unsubscribe;\n}\n\nexport interface Observable {\n // Subscribe method\n subscribe: Subscribe;\n}\n\nexport type Executor = (observer: Observer) => 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(\n executor: Executor,\n onNoObservers?: Executor\n): Subscribe {\n const proxy = new ObserverProxy(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 implements Observer {\n private observers: Array> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor | 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, onNoObservers?: Executor) {\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) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer) => {\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 | PartialObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer;\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;\n } else {\n observer = {\n next: nextOrObserver as NextFn,\n error,\n complete\n } as Observer;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn;\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);\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) => 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) => 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 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 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 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 *

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 *

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 {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\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;\n exchangeTokenPromise?: Promise;\n tokenRefresher?: Refresher;\n reCAPTCHAState?: ReCAPTCHAState;\n isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n initialized: Deferred;\n widgetId?: string;\n // True if the most recent recaptcha check succeeded.\n succeeded?: boolean;\n}\n\nexport interface DebugState {\n initialized: boolean;\n enabled: boolean;\n token?: Deferred;\n}\n\nconst APP_CHECK_STATES = new Map();\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 | null = null;\n private nextErrorWaitInterval: number;\n constructor(\n private readonly operation: () => Promise,\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 {\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 {\n return new Promise(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 = {\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(\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 {\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 | null = null;\nfunction getDBPromise(): Promise {\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 {\n return read(computeKey(app)) as Promise;\n}\n\nexport function writeTokenToIndexedDB(\n app: FirebaseApp,\n token?: AppCheckTokenInternal\n): Promise {\n return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise {\n return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise {\n return read(DEBUG_TOKEN_KEY) as Promise;\n}\n\nasync function write(key: string, value: unknown): Promise {\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 {\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 {\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 {\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 {\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 {\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();\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\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 {\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\n/**\n * Internal API for limited use tokens. Skips all FAC state and simply calls\n * the underlying provider.\n */\nexport async function getLimitedUseToken(\n appCheck: AppCheckService\n): Promise {\n const app = appCheck.app;\n ensureActivated(app);\n\n const { provider } = getStateReference(app);\n\n if (isDebugMode()) {\n const debugToken = await getDebugToken();\n const { token } = await exchangeToken(\n getExchangeDebugTokenRequest(app, debugToken),\n appCheck.heartbeatServiceProvider\n );\n return { token };\n } else {\n // provider is definitely valid since we ensure AppCheck was activated\n const { token } = await provider!.getToken();\n return { token };\n }\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 getLimitedUseToken,\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 {\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 getLimitedUseToken: () => getLimitedUseToken(appCheck),\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 {\n const initialized = new Deferred();\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 {\n const initialized = new Deferred();\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\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 {\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 // Success callback - set state\n callback: () => {\n getStateReference(app).reCAPTCHAState!.succeeded = true;\n },\n // Failure callback - set state\n 'error-callback': () => {\n getStateReference(app).reCAPTCHAState!.succeeded = false;\n }\n });\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;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n callback: () => void;\n 'error-callback': () => void;\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 { getStateReference } from './state';\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 {\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 // Check if a failure state was set by the recaptcha \"error-callback\".\n if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\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 {\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 // Check if a failure state was set by the recaptcha \"error-callback\".\n if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\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 {\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 getLimitedUseToken as getLimitedUseTokenInternal,\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 {\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 * Requests a Firebase App Check token. This method should be used\n * only if you need to authorize requests to a non-Firebase backend.\n *\n * Returns limited-use tokens that are intended for use with your\n * non-Firebase backend endpoints that are protected with\n * \n * Replay Protection. This method\n * does not affect the token generation behavior of the\n * #getAppCheckToken() method.\n *\n * @param appCheckInstance - The App Check service instance.\n * @returns The limited use token.\n * @public\n */\nexport function getLimitedUseToken(\n appCheckInstance: AppCheck\n): Promise {\n return getLimitedUseTokenInternal(appCheckInstance as AppCheckService);\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\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,\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 = () => {};\n let errorFn: ErrorFn = () => {};\n if ((onNextOrObserver as PartialObserver).next != null) {\n nextFn = (\n onNextOrObserver as PartialObserver\n ).next!.bind(onNextOrObserver);\n } else {\n nextFn = onNextOrObserver as NextFn;\n }\n if (\n (onNextOrObserver as PartialObserver).error != null\n ) {\n errorFn = (\n onNextOrObserver as PartialObserver\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 {\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 {\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\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 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;\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 {\n return new Promise(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 { 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 { 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>();\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(\n component: Component\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 { 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 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): 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 { 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();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent(\n app: FirebaseApp,\n component: Component\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(\n component: Component\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(\n app: FirebaseApp,\n name: T\n): Provider {\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(\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 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;\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 {\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 {\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;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise {\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 {\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 {\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 {\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 * @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 {\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 | 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,\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): 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\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 {\n private component: Component | null = null;\n private readonly instances: Map = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred\n > = new Map();\n private readonly instancesOptions: Map> =\n new Map();\n private onInitCallbacks: Map>> = 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 {\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();\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 | null {\n return this.component;\n }\n\n setComponent(component: Component): 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 {\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 {\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, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set>();\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;\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(component: Component): 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>();\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(component: Component): 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(component: Component): 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(name: T): Provider {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider(name, this);\n this.providers.set(name, provider as unknown as Provider);\n\n return provider as Provider;\n }\n\n getProviders(): Array> {\n return Array.from(this.providers.values());\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 { 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\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 {\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 {\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\n | null\n | ((a: UploadTaskSnapshotCompat) => unknown),\n error?: ((error: StorageError) => void) | null,\n completed?: () => void | null\n ): Unsubscribe | Subscribe {\n let wrappedNextOrObserver:\n | StorageObserver\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 = (\n next?: NextFn | StorageObserver,\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 = (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 {\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\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 {\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 {\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 {\n return getMetadata(this._delegate) as Promise;\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 {\n return updateMetadata(\n this._delegate,\n metadata as SettableMetadata\n ) as Promise;\n }\n\n /**\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\n getDownloadURL(): Promise {\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 {\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"],"names":["_getCurrentScheme","_a","self","location","protocol","_isAndroidOrIosCordovaScheme","ua","getUA","toLowerCase","match","_isLocalStorageNotSynchronized","isIE","document","documentMode","test","_isEdge","_isWebStorageSupported","storage","localStorage","key","exp","isIndexedDBAvailable","e","_isWorker","global","_isPopupRedirectSupported","isBrowserExtension","isReactNative","isNode","_isLikelyCordova","Persistence","LOCAL","NONE","SESSION","_assert$3","PERSISTENCE_KEY","async","_savePersistenceForRedirect","auth","_initializationPromise","session","getSessionStorageIfAvailable","config","apiKey","name","setItem","_getPersistence","window","sessionStorage","_assert$2","CompatPopupRedirectResolver","constructor","browserResolver","cordovaResolver","underlyingResolver","_redirectPersistence","_completeRedirectFn","_overrideRedirectResult","this","selectUnderlyingResolver","assertedUnderlyingResolver","_initialize","provider","authType","eventId","_openPopup","_openRedirect","_isIframeWebStorageSupported","cb","_originValidation","_shouldInitProactively","isCordova","Promise","resolve","timeoutId","setTimeout","addEventListener","clearTimeout","_isCordova","unwrap","object","credentialFromObject","_tokenResponse","FirebaseError","customData","providerId","oauthIdToken","oauthAccessToken","oauthTokenSecret","pendingToken","nonce","startsWith","signInMethod","idToken","accessToken","credential","rawNonce","credentialFromError","credentialFromResult","convertCredential","credentialPromise","catch","response","code","resolver","MultiFactorResolver","credErr","tenantId","undefined","email","phoneNumber","attachExtraErrorFields","then","operationType","user","userCredential","additionalUserInfo","User","getOrCreate","convertConfirmationResult","confirmationResultPromise","confirmationResultExp","verificationId","confirm","verificationCode","wrapped","hints","resolveSignIn","assertion","_delegate","multiFactor","static","USER_MAP","has","set","get","delete","reload","toJSON","getIdTokenResult","forceRefresh","getIdToken","linkAndRetrieveDataWithCredential","linkWithCredential","applicationVerifier","reauthenticateAndRetrieveDataWithCredential","reauthenticateWithCredential","reauthenticateWithPhoneNumber","reauthenticateWithPopup","sendEmailVerification","actionCodeSettings","updateEmail","newEmail","updatePassword","newPassword","updatePhoneNumber","phoneCredential","updateProfile","profile","verifyBeforeUpdateEmail","emailVerified","isAnonymous","metadata","providerData","refreshToken","displayName","photoURL","uid","WeakMap","_assert$1","Auth","app","isInitialized","getImmediate","linkUnderlyingAuth","options","appName","initialize","persistence","buildPersistenceHierarchy","popupRedirectResolver","_updateErrorMap","emulatorConfig","currentUser","languageCode","settings","tid","useDeviceLanguage","signOut","useEmulator","url","applyActionCode","checkActionCode","confirmPasswordReset","password","fetchProvidersForEmail","fetchSignInMethodsForEmail","isSignInWithEmailLink","emailLink","addFrameworkForLogging","framework","onAuthStateChanged","nextOrObserver","errorFn","completed","next","error","complete","wrapObservers","onIdTokenChanged","sendSignInLinkToEmail","sendPasswordResetEmail","converted","Object","values","includes","_validatePersistenceArgument","_isAvailable","setPersistence","signInAndRetrieveDataWithCredential","signInWithCredential","signInAnonymously","signInWithCustomToken","token","signInWithEmailAndPassword","signInWithEmailLink","signInWithPhoneNumber","updateCurrentUser","verifyPasswordResetCode","_delete","oldNext","persistences","getItem","_getPersistencesFromRedirect","push","PhoneAuthProvider","firebase","verifyPhoneNumber","phoneInfoOptions","PHONE_SIGN_IN_METHOD","PROVIDER_ID","_assert","RecaptchaVerifier","container","parameters","type","clear","render","verify","instance","INTERNAL","registerComponent","Component","getProvider","authProvider","setServiceProps","ActionCodeInfo","Operation","EMAIL_SIGNIN","PASSWORD_RESET","RECOVER_EMAIL","REVERT_SECOND_FACTOR_ADDITION","VERIFY_AND_CHANGE_EMAIL","VERIFY_EMAIL","EmailAuthProvider","FacebookAuthProvider","GithubAuthProvider","GoogleAuthProvider","OAuthProvider","SAMLAuthProvider","PhoneMultiFactorGenerator","TwitterAuthProvider","AuthCredential","Error","setInstantiationMode","setMultipleInstances","registerVersion","SDK_VERSION","setSDKVersion","version","DOMStorageWrapper","domStorage_","prefix_","value","removeItem","prefixedName_","stringify","storedVal","jsonEval","remove","toString","MemoryStorage","cache_","isInMemoryStorage","contains","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","logClient","Logger","LUIDGenerator","id","sha1","str","utf8Bytes","stringToByteArray","Sha1","update","sha1Bytes","digest","base64","buildLogMessage_","varArgs","message","i","length","arg","Array","isArray","apply","logger","firstLog_","enableLogging$1","logger_","persistent","assert","logLevel","LogLevel","log","bind","logWrapper","prefix","fatal","warn","isInvalidJSONNumber","data","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","MIN_NAME","MAX_NAME","nameCompare","a","b","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","obj","ObjectToUniqueKey","keys","k","sort","splitStringBySize","segsize","len","dataSegs","c","substring","each","fn","hasOwnProperty","doubleToIEEE754String","v","bias","s","f","ln","Infinity","Math","abs","pow","min","floor","LN2","round","bits","reverse","join","hexByteString","hexByte","parseInt","substr","INTEGER_REGEXP_","RegExp","intVal","exceptionGuard","stack","setTimeoutNonBlocking","time","timeout","Deno","unrefTimer","AppCheckTokenProvider","appName_","appCheckProvider","appCheck","optional","getToken","reject","addTokenChangeListener","listener","addTokenListener","notifyForInvalidToken","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth_","onInit","addAuthTokenListener","removeTokenChangeListener","removeAuthTokenListener","errorMessage","EmulatorTokenProvider","OWNER","PROTOCOL_VERSION","FORGE_DOMAIN_RE","APP_CHECK_TOKEN_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","host","secure","namespace","webSocketOnly","nodeAdmin","persistenceKey","includeNamespaceInQueryParams","isUsingEmulator","_host","_domain","indexOf","internalHost","isCacheableHost","isCustomHost","newHost","toURLString","query","repoInfoConnectionURL","repoInfo","params","connURL","repoInfoNeedsQueryParam","pairs","StatsCollection","counters_","incrementCounter","amount","deepCopy","collections","reporters","statsManagerGetCollection","hashString","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","callback","handleResponse","requestNum","toProcess","FIREBASE_LONGPOLL_START_PARAM","BrowserPollConnection","connId","applicationId","appCheckToken","authToken","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","open","onMessage","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","isNodeSdk","readyState","called","wrappedFn","body","attachEvent","executeWhenDOMReady","scriptTagHolder","FirebaseIFrameScriptHolder","args","command","arg1","arg2","arg3","arg4","incrementIncomingBytes_","sendNewPolls","pN","urlParams","random","uniqueCallbackIdentifier","hostname","connectURL","addTag","start","startLongPoll","addDisconnectPingFrame","forceAllow_","forceDisallow_","createElement","href","Windows","UI","markConnectionHealthy","shutdown_","close","myDisconnFrame","removeChild","send","dataStr","base64data","base64Encode","MAX_URL_DATA_SIZE","enqueueSegment","pw","src","style","display","appendChild","commandCB","onMessageCB","outstandingRequests","Set","pendingSegs","currentSerial","myIFrame","createIFrame_","script","domain","iframeContents","doc","write","iframe","contentWindow","contentDocument","alive","textContent","myID","myPW","newRequest_","size","theURL","curDataString","d","theSeg","shift","seg","ts","addLongPollTag_","segnum","totalsegs","serial","add","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript","onload","onreadystatechange","rstate","parentNode","onerror","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","headers","process","platform","env","proxy","origin","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","navigator","userAgent","oldAndroidRegex","oldAndroidMatch","parseFloat","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","isNaN","mess","resetKeepAlive","remainingData","sendString_","String","clearInterval","setInterval","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","ALL_TRANSPORTS","IS_TRANSPORT_INITIALIZED","globalTransportInitialized_","isWebSocketsAvailable","isSkipPollConnection","previouslyFailed","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","msg","t","sendData_","tryCleanupConnection","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onDataMessage_","onPrimaryResponse_","payload","handshakePayload","assign","h","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","sessionId","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","closeConnections_","reason","ServerActions","put","pathString","onComplete","hash","merge","refreshAuthToken","refreshAppCheckToken","onDisconnectPut","onDisconnectMerge","onDisconnectCancel","reportStats","stats","EventEmitter","allowedEvents_","listeners_","trigger","eventType","listeners","context","on","validateEventType_","eventData","getInitialEvent","off","splice","find","et","OnlineMonitor","super","online_","isMobileCordova","currentlyOnline","MAX_PATH_DEPTH","MAX_PATH_LENGTH_BYTES","Path","pathOrString","pieceNum","pieces_","split","copyTo","pieceNum_","newEmptyPath","pathGetFront","path","pathGetLength","pathPopFront","pathGetBack","pathSlice","begin","slice","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathCompare","left","right","leftKeys","rightKeys","cmp","pathEquals","other","j","pathContains","ValidationPath","errorPrefix_","parts_","byteLength_","max","stringLength","validationPathCheckValid","validationPath","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible_","visible","RECONNECT_MIN_DELAY","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens","Map","outstandingPuts_","outstandingGets_","outstandingPutCount_","outstandingGetCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","forceTokenRefresh_","invalidAuthTokenCount_","invalidAppCheckTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","getInstance","onVisible_","onOnline_","action","onResponse","curReqNum","r","initConnection_","deferred","Deferred","outstandingGet","request","p","_path","q","_queryObject","index","sendGet_","promise","listen","currentHashFn","tag","queryId","_queryIdentifier","_queryParams","isDefault","loadsAllData","listenSpec","hashFn","sendListen_","req","status","warnOnListenWarnings_","removeListen_","warnings","safeGet","indexSpec","getIndex","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","isAdmin","tryAppCheck","authMethod","isValidFormat","requestData","cred","res","onAuthRevoked_","onAppCheckRevoked_","unlisten","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","result","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","Date","getTime","handleTimestamp_","sendConnectStats_","restoreState_","scheduleConnect_","establishConnection_","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage","onReady","nextConnectionId_","canceled","connection","closeFn","sendRequestFn","all","interrupt","resume","isEmpty","delta","serverTimeOffset","map","normalizedPathString","statusCode","explanation","console","replace","queries","clientName","NamedNode","node","Index","getCompare","compare","indexedValueChanged","oldNode","newNode","oldWrapped","newWrapped","minPost","MIN","__EMPTY_NODE","KeyIndex","val","isDefinedOn","assertionError","maxPost","makePost","indexValue","KEY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","getNext","pop","hasNext","peek","LLRBNode","color","RED","SortedMap","EMPTY_NODE","copy","count","inorderTraversal","reverseTraversal","min_","minKey","maxKey","insert","n","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$2","priorityHashText","priority","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","nodeFromJSON$1","MAX_NODE$1","LeafNode","value_","priorityNode_","lazyHash_","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","hasChild","getPredecessorChildName","childNode","updateImmediateChild","newChildNode","updateChild","front","numChildren","forEachChild","exportFormat","getValue","toHash","compareTo","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","withIndex","isIndexed","equals","PRIORITY_INDEX","aPriority","bPriority","indexCmp","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","low","high","namedNode","middle","root","base12","buildPennant","chunkSize","childTree","attachPennant","pennant","isOne","buildFrom12Array","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","Default","indexKey","sortedMap","hasIndex","indexDefinition","addIndex","existingChildren","sawIndexedValue","iter","Wrap","newIndex","indexName","newIndexSet","newIndexes","addToIndexes","indexedChildren","existingSnap","newChildren","removeFromIndexes","ChildrenNode","children_","indexMap_","child","newIndexMap","newPriority","newImmediateChild","numKeys","allIntegerKeys","array","childHash","idx","resolveIndex_","predecessor","getFirstChildName","getFirstChild","getLastChildName","getLastChild","wrappedNode","startPost","iterator","endPost","MAX_NODE","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","defineProperties","MAX","setMaxNode","USE_HINZE","nodeFromJSON","json","childData","children","childrenHavePriority","childSet","sortedChildSet","setNodeFromJSON","PathIndex","indexPath_","extractChild","snap","aChild","bChild","valueNode","VALUE_INDEX","changeValue","snapshotNode","changeChildAdded","changeChildRemoved","changeChildChanged","oldSnap","IndexedFilter","index_","newChild","affectedPath","source","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","startIsInclusive_","startAfterSet_","endIsInclusive_","endBeforeSet_","getStartPost","getEndPost","matches","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","startParam","endParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listens_","listenId","getListenId_","thisListen","queryStringParameters","restRequest_","querystring","xhr","XMLHttpRequest","responseText","SnapshotHolder","rootNode_","getNode","updateSnapshot","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","sparseSnapshotTreeForget","tree","sparseSnapshotTreeForEachTree","prefixPath","func","forEach","sparseSnapshotTreeForEachChild","StatsListener","collection_","last_","newStats","stat","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","reportedStats","haveStatsToReport","OperationType","newOperationSourceServerTaggedQuery","fromUser","fromServer","tagged","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_","eventGeneratorGenerateEventsForType","eventGenerator","events","changes","registrations","eventCache","filteredChanges","filter","change","aWrapped","bWrapped","eventGeneratorCompareChanges","materializedChange","prevName","eventGeneratorMaterializeSingleChange","registration","respondsTo","createEvent","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","ImmutableTree","EmptyChildren","childPath","findRootMostMatchingPathAndValue","relativePath","predicate","childExistingPathAndValue","findRootMostValueAndPath","toSet","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","CompoundWrite","writeTree_","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","newWriteTree","compoundWriteAddWrites","updates","newWrite","compoundWriteRemoveWrite","empty","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeRemoveWrite","writeId","allWrites","findIndex","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeTreeRecordContainsPath_","visibleWrites","writeTreeLayerTree_","writeTreeDefaultFilter_","lastWriteId","writeTreeResetTree_","writeRecord","writes","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","subMerge","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeShadowingWrite","writeTreeRefCalcIndexedSlice","completeServerData","toIterate","nodes","writeTreeCalcIndexedSlice","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeCalcCompleteChild","writeTreeRefChild","ChildChangeAccumulator","changeMap","oldChange","oldType","getChanges","from","NO_COMPLETE_CHILD_SOURCE","getCompleteChild","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","viewProcessorApplyOperation","viewProcessor","oldViewCache","operation","writesCache","completeCache","accumulator","filterServerNode","overwrite","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_","newViewProcessor","initialServerCache","initialEventCache","eventGenerator_","viewGetCompleteServerCache","view","cache","viewIsEmpty","viewRemoveEventRegistration","eventRegistration","cancelError","cancelEvents","maybeEvent","createCancelEvent","remaining","existing","hasAnyCallback","concat","viewApplyOperation","viewGenerateEventsForChanges_","eventRegistrations","moves","eventGeneratorGenerateEventsForChanges","referenceConstructor$1","referenceConstructor","SyncPoint","views","syncPointApplyOperation","syncPoint","optCompleteServerCache","syncPointGetView","serverCacheComplete","eventCacheComplete","syncPointAddEventRegistration","viewAddEventRegistration","initialChanges","viewGetInitialEvents","syncPointRemoveEventRegistration","removed","hadCompleteView","syncPointHasCompleteView","viewQueryId","entries","_repo","syncPointGetQueryViews","syncPointGetCompleteServerCache","syncPointViewForQuery","syncPointGetCompleteView","syncPointViewExistsForQuery","syncTreeNextQueryTag_","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","tagToQueryMap","queryToTagMap","syncTreeApplyUserOverwrite","syncTree","newData","writeTreeAddOverwrite","syncTreeApplyOperationToSyncPoints_","syncTreeApplyUserMerge","writeTreeAddMerge","changeTree","fromObject","syncTreeAckUserWrite","record","writeTreeGetWrite","syncTreeApplyServerOverwrite","syncTreeRemoveEventRegistration","skipListenerDedup","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","maybeChildSyncPoint","childMap","_key","childViews","syncTreeCollectDistinctViewsForSubTree_","newQuery","syncTreeCreateListenerForView_","startListening","syncTreeQueryForListening_","syncTreeTagForQuery","defaultTag","stopListening","queryToRemove","tagToRemove","syncTreeMakeQueryKey_","removedQuery","removedQueryKey","removedQueryTag","syncTreeRemoveTags_","syncTreeApplyTaggedQueryOverwrite","queryKey","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryPath","syncTreeApplyTaggedOperation_","syncTreeAddEventRegistration","skipSetupListener","foundAncestorDefaultView","pathToSyncPoint","sp","childSyncPoint","viewAlreadyExists","queriesToStop","childQueries","queryToStop","syncTreeSetupListener_","syncTreeCalcCompleteEventCache","syncTreeGetServerValue","serverCacheNode","viewGetCompleteNode","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","viewGetServerCache","syncTreeApplyTaggedListenComplete","syncTreeApplyListenComplete","toUpperCase","errorForServerCode","splitIndex","ExistingValueProvider","DeferredValueProvider","syncTree_","path_","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","JSON","op","unused","existingNode","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","childCount","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeForEachChild","treeForEachDescendant","includeSelf","childrenFirst","treeGetPath","childEmpty","treeIsEmpty","childExists","treeUpdateChild","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidPriority","validateFirebaseDataArg","fnName","validateFirebaseData","errorPrefix","hasDotValue","hasActualChild","validationPathPush","last","validationPathPop","validateFirebaseMergeDataArg","errorPrefix$1","mergePaths","curPath","prevPath","validateFirebaseMergePaths","validatePriority","validateKey","argumentName","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","isValidRootPathString","EventQueue","eventLists_","recursionDepth_","eventQueueQueueEvents","eventQueue","eventDataList","currList","getPath","eventQueueRaiseEventsAtPath","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventQueueRaiseEventsForChangedPath","changedPath","sentAll","eventList","eventListRaise","eventFn","getEventRunner","INTERRUPT_REASON","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","transactionQueueTree_","persistentConnection_","repoStart","repo","appId","authOverride","search","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoUpdateInfo","repoOnServerInfoUpdate","statsReporter_","creatorFunction","statsManagerGetOrCreateReporter","infoData_","infoSyncTree_","infoEvents","serverSyncTree_","repoServerTime","offset","repoGenerateServerValues","taggedChildren","raw","syncTreeApplyTaggedQueryMerge","taggedSnap","syncTreeApplyServerMerge","repoRerunTransactions","repoLog","resolvedOnDisconnectTree","resolved","repoAbortTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoSetWithPriority","newVal","newNodeUnresolved","success","clearEvents","repoCallOnCompleteCallback","repoOnDisconnectCancel","repoOnDisconnectSet","repoRemoveEventCallbackForQuery","repoInterrupt","repoGetLatestState","excludeSets","repoSendReadyTransactions","repoPruneCompletedTransactionsBelowNode","queue","repoBuildTransactionQueue","every","transaction","setsToIgnore","txn","currentWriteId","latestState","snapToSend","latestHash","retryCount","currentOutputSnapshotRaw","dataToSend","pathToSend","callbacks","currentOutputSnapshotResolved","unwatcher","abortReason","repoSendTransactionQueue","rootMostTransactionNode","repoGetAncestorTransactionNode","txnsToRerun","abortTransaction","currentNode","currentInputSnapshot","newDataNode","oldWriteId","newNodeResolved","applyLocally","repoRerunTransactionQueue","transactionNode","transactionQueue","repoAggregateTransactionQueuesForNode","order","nodeQueue","to","treeForEachAncestor","repoAbortTransactionsOnNode","lastSent","parseRepoInfo","dataURL","parseDatabaseURL","scheme","subdomain","port","colonInd","slashInd","questionMarkInd","pathStringDecoded","piece","decodeURIComponent","decodePath","queryString","results","charAt","segment","kv","decodeQuery","hostWithoutPort","dotInd","PUSH_CHARS","nextPushId","lastPushTime","lastRandChars","now","duplicateTime","timeStampChars","DataEvent","snapshot","ref","getEventType","exportVal","CancelEvent","CallbackContext","snapshotCallback","cancelCallback","onValue","expDataSnapshot","previousChildName","call","onCancel","hasCancelCallback","userCallback","OnDisconnect","cancel","wrapCallback","setWithPriority","repoOnDisconnectSetWithPriority","childrenToMerge","repoOnDisconnectUpdate","QueryImpl","_orderByCalled","ReferenceImpl","isEqual","getModularInstance","sameRepo","samePath","sameQueryIdentifier","encodeURIComponent","pathToUrlEncodedString","validateNoPreviousOrderByCall","validateQueryEndpoints","startNode","endNode","tooManyArgsError","wrongArgTypeError","validateLimit","parentPath","DataSnapshot","_node","_index","childRef","exists","hasChildren","db","_checkNotDeleted","_root","refFromURL","parsedURL","changedKey","changedValue","repoUpdate","callbackContext","ValueEventRegistration","cached","err","repoGetValue","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","syncPointSetReferenceConstructor","syncTreeSetReferenceConstructor","FIREBASE_DATABASE_EMULATOR_HOST_VAR","repos","useRestClient","repoManagerDatabaseFromApp","dbUrl","databaseURL","projectId","isEmulator","dbEmulatorHost","authTokenProvider","appRepos","repoManagerCreateRepo","Database","_repoInternal","_instanceStarted","_rootInternal","repoManagerDeleteRepo","apiName","checkTransportInit","forceWebSockets","forceDisallow","forceLongPolling","forceAllow","connectDatabaseEmulator","tokenProvider","mockUserToken","createMockUserToken","repoManagerApplyEmulatorSettings","goOnline","enableLogging","SERVER_TIMESTAMP","TransactionResult","committed","runTransaction","transactionUpdate","currentState","queueNode","priorityForNode","repoStartTransaction","promiseComplete","prototype","simpleListen","echo","onEcho","variant","SDK_VERSION$1","_registerComponent","instanceIdentifier","validateArgCount","arguments","validateCallback","objectToMerge","newObjectToMerge","_database","_validatePathString","getRef","Reference","Query","database","cancelCallbackOrContext","ret","getCancelAndContextArgs_","valueCallback","expSnapshot","validateEventType","validateContextObject","once","failureCallbackOrContext","limitToFirst","limit","limitToLast","orderByChild","orderByKey","orderByPriority","orderByValue","startAt","startAfter","endAt","endBefore","equalTo","cancelOrContext","_ReferenceImpl","_QueryImpl","_QueryParams","getKey","getParent","getRoot","_validateWritablePath","bool","validateBoolean","transactionResult","setPriority","expPromise","thennablePushRef","pushRef","expRef","OnDisconnect$1","goOffline","ServerValue","TIMESTAMP","increment","customAuthImpl","_setSDKVersion","Provider","ComponentContainer","setComponent","_repoManagerDatabaseFromApp","databaseExp","identifier","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","StorageError","status_","prependCode","serverResponse","_baseMessage","setPrototypeOf","_codeEquals","StorageErrorCode","ErrorCode","unknown","UNKNOWN","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","CANCELED","cannotSliceBlob","CANNOT_SLICE_BLOB","invalidArgument","INVALID_ARGUMENT","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","Location","bucket","isRoot","fullServerUrl","encode","bucketOnlyServerUrl","bucketString","bucketLocation","makeFromUrl","INVALID_DEFAULT_BUCKET","bucketDomain","gsRegex","httpModify","loc","firebaseStorageHost","groups","regex","indices","postModify","group","captures","exec","bucketValue","pathValue","INVALID_URL","invalidUrl","FailRequest","promise_","getPromise","_appDelete","isString","isNativeBlob","isNativeBlobDefined","Blob","validateNumber","argument","minValue","maxValue","makeUrl","urlPart","makeQueryString","queryPart","isRetryStatusCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","isAdditionalRetryCode","NetworkRequest","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","timeout_","progressCallback_","connectionFactory_","retry","pendingConnection_","backoffId_","canceled_","appDelete_","resolve_","reject_","doTheRequest","backoffCallback","RequestEndStatus","progressListener","progressEvent","loaded","total","lengthComputable","addUploadProgressListener","removeUploadProgressListener","hitServer","getErrorCode","NO_ERROR","getStatus","wasCanceled","ABORT","successCode","backoffDone","requestWentThrough","wasSuccessCode","getResponse","getErrorText","doRequest","backoffCompleteCb","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","millis","responseHandler","clearGlobalTimeout","waitMillis","stopped","stop","wasTimeout","appDelete","abort","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob$1","bb","append","getBlob","UNSUPPORTED_ENVIRONMENT","decodeBase64","encoded","atob","polyFill","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","contentType","dataFromString","stringData","utf8Bytes_","base64Bytes_","dataUrl","parts","DataURLParts","rest","decoded","percentEncodedBytes_","dataURLBytes_","charCodeAt","Uint8Array","hasMinus","hasUnder","hasPlus","hasSlash","bytes","end","endsWith","FbsBlob","elideCopy","blobType","data_","ArrayBuffer","byteLength","size_","type_","startByte","endByte","sliced","blob","webkitSlice","mozSlice","sliceBlob","buffer","blobby","uint8Arrays","finalLength","merged","uploadData","jsonObjectOrNull","parse","lastComponent","lastIndexOf","noXform_","Mapping","server","local","writable","xform","mappings_","getMappings","mappings","nameMapping","_metadata","fullPath","xformPath","sizeMapping","fromResource","service","resource","mapping","defineProperty","_makeStorageReference","addRef","fromResourceString","resourceString","toResourceString","PREFIXES_KEY","ITEMS_KEY","fromResponseString","listResult","prefixes","items","nextPageToken","pathWithoutTrailingSlash","reference","item","fromBackendResponse","RequestInfo","method","handler","errorHandler","progressCallback","successCodes","handlerCheck","cndn","metadataHandler","text","downloadUrlHandler","tokens","alt","downloadUrlFromResourceString","_protocol","sharedErrorHandler","newErr","UNAUTHORIZED_APP","UNAUTHENTICATED","QUOTA_EXCEEDED","UNAUTHORIZED","objectErrorHandler","shared","OBJECT_NOT_FOUND","getMetadata$2","maxOperationRetryTime","requestInfo","list$2","delimiter","pageToken","maxResults","listHandler","metadataForUpload_","metadataClone","determineContentType_","multipartUpload","boundary","genBoundary","metadata_","preBlobPart","postBlobPart","maxUploadRetryTime","ResumableUploadStatus","current","finalized","checkResumeHeader_","allowed","getResponseHeader","RESUMABLE_UPLOAD_CHUNK_SIZE","continueResumableUpload","SERVER_FILE_WRONG_SIZE","bytesLeft","bytesToUpload","uploadCommand","uploadStatus","newCurrent","TaskEvent","STATE_CHANGED","TaskState","RUNNING","PAUSED","SUCCESS","ERROR","taskStateFromInternalTaskState","state","Observer","observer","argsToForward","textFactoryOverride","XhrConnection","sent_","xhr_","initXhr","errorCode_","sendPromise_","NETWORK_ERROR","setRequestHeader","statusText","header","upload","removeEventListener","XhrTextConnection","responseType","newTextConnection","UploadTask","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_reject","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","completeTransitions_","backoffExpired","isExponentialBackoffExpired","sleepTime","_transition","_metadataErrorHandler","maxSleepTime","_promise","_start","_makeProgressCallback","sizeBefore","_updateProgress","_createResumable","_fetchStatus","_fetchMetadata","pendingTimeout","_continueUpload","_oneShotUpload","_resolveToken","_getAuthToken","_getAppCheckToken","metadataForUpload","createResumableUpload","_location","createRequest","_makeRequest","sizeString","getResumableUploadStatus","statusRequest","uploadRequest","newStatus","_increaseMultiplier","metadataRequest","multipartRequest","transferred","old","_notifyObservers","wasPaused","externalState","bytesTransferred","totalBytes","task","_addObserver","_removeObserver","onFulfilled","onRejected","_notifyObserver","_finishPromise","triggered","valid","pause","_service","_newRef","newPath","_throwIfRoot","listAll$1","listAllHelper","opt","nextPage","list$1","makeRequestWithTokens","updateMetadata$1","updateMetadata$2","getDownloadURL$1","getDownloadUrl","NO_DOWNLOAD_URL","deleteObject$1","_xhr","_text","deleteObject$2","_getChild$1","canonicalChildPath","component","refFromPath","FirebaseStorageImpl","_bucket","NO_DEFAULT_BUCKET","ref$1","serviceOrRef","pathOrUrl","extractBucket","makeFromBucketSpec","_authProvider","_appCheckProvider","_url","_firebaseVersion","_appId","_deleted","_maxOperationRetryTime","_maxUploadRetryTime","_requests","_overrideAuthToken","tokenData","requestFactory","firebaseVersion","addGmpidHeader_","addAuthHeader_","addVersionHeader_","addAppCheckHeader_","makeRequest","STORAGE_TYPE","uploadBytesResumable","uploadBytesResumable$1","getMetadata","getMetadata$1","updateMetadata","list","listAll","getDownloadURL","deleteObject","_getChild","connectStorageEmulator","connectStorageEmulator$1","factory","CONSTANTS","NODE_CLIENT","NODE_ADMIN","stringToByteArray$1","out","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","encodeByteArray","input","webSafe","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","decodeString","pos","c1","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","byte4","DecodeBase64StringError","base64urlEncodeWithoutPadding","base64Decode","deepExtend","target","prop","getGlobal","getDefaults","__FIREBASE_DEFAULTS__","getDefaultsFromEnvVariable","defaultsJsonString","getDefaultsFromCookie","cookie","info","getDefaultAppConfig","getExperimentalSetting","project","iat","sub","user_id","iss","aud","auth_time","sign_in_provider","identities","alg","forceEnvironment","isBrowser","runtime","chrome","browser","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","onsuccess","deleteDatabase","onupgradeneeded","captureStackTrace","ErrorFactory","create","serviceName","errors","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","decode","claims","signature","issuedAtTime","contextObj","deepEqual","aKeys","bKeys","aProp","bProp","isObject","thing","querystringParams","arrayVal","querystringDecode","extractQuerystring","queryStart","fragmentStart","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","W","lengthMinusBlock","inbuf","totalBits","createSubscribe","executor","onNoObservers","ObserverProxy","subscribe","observers","unsubscribes","observerCount","forEachObserver","methods","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","minCount","maxCount","argCount","argError","argName","uuidv4","DEFAULT_INTERVAL_MILLIS","DEFAULT_BACKOFF_FACTOR","MAX_VALUE_MILLIS","RANDOM_FACTOR","calculateBackoffMillis","backoffCount","intervalMillis","backoffFactor","currBaseValue","randomWait","APP_CHECK_STATES","DEFAULT_STATE","activated","tokenObservers","DEBUG_STATE","initialized","enabled","getStateReference","getDebugState","BASE_ENDPOINT","EXCHANGE_DEBUG_TOKEN_METHOD","TOKEN_REFRESH_TIME","OFFSET_DURATION","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","Refresher","retryPolicy","getWaitDuration","lowerBound","upperBound","pending","nextErrorWaitInterval","isRunning","hasSucceeded","ms","getNextRun","currentErrorWaitInterval","ERRORS","ERROR_FACTORY","getRecaptcha","isEnterprise","grecaptcha","enterprise","ensureActivated","getDurationString","durationInMillis","totalSeconds","days","hours","minutes","seconds","pad","exchangeToken","heartbeatServiceProvider","heartbeatService","heartbeatsHeader","getHeartbeatsHeader","responseBody","fetch","originalError","originalErrorMessage","httpStatus","ttl","timeToLiveAsNumber","expireTimeMillis","issuedAtTimeMillis","getExchangeDebugTokenRequest","debugToken","debug_token","DB_NAME","DB_VERSION","STORE_NAME","DEBUG_TOKEN_KEY","dbPromise","getDBPromise","event","oldVersion","createObjectStore","keyPath","objectStore","compositeKey","_event","read","computeKey","readTokenFromStorage","readTokenFromIndexedDB","writeTokenToStorage","writeTokenToIndexedDB","readOrCreateDebugTokenFromStorage","existingDebugToken","_e","newToken","isDebugMode","getDebugToken","defaultTokenErrorData","getToken$2","isValid","cachedToken","cachedTokenPromise","interopTokenResult","shouldCallListeners","exchangeTokenPromise","finally","tokenFromDebugExchange","makeDummyTokenResult","notifyTokenListeners","getLimitedUseToken$1","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","head","loadReCAPTCHAV3Script","initializeEnterprise","loadReCAPTCHAEnterpriseScript","ready","widgetId","sitekey","succeeded","error-callback","renderInvisibleWidget","invisibleDiv","getToken$1","recaptcha","execute","ReCaptchaV3Provider","_siteKey","_throttleData","throwIfThrottled","attestedClaimsToken","_app","reCAPTCHAToken","getExchangeRecaptchaV3TokenRequest","_heartbeatServiceProvider","_b","setBackoff","_c","allowRequestsAfter","_getProvider","otherProvider","ReCaptchaEnterpriseProvider","getExchangeRecaptchaEnterpriseTokenRequest","CustomProvider","_customProviderOptions","customToken","issuedAtTimeSeconds","throttleData","backoffMillis","initializeAppCheck","getApp","globals","debugState","FIREBASE_APPCHECK_DEBUG_TOKEN","deferredToken","initializeDebugMode","existingInstance","initialOptions","getOptions","setInitialState","automaticDataCollectionEnabled","_activate","APP_CHECK_NAME_INTERNAL","setInstanceCreatedCallback","_identifier","_appcheckService","getLimitedUseToken","internalFactory","activate","siteKeyOrProvider","setTokenAutoRefreshEnabled","appCheckInstance","onTokenChanged","onNextOrObserver","onCompletion","nextFn","FirebaseAppImpl","_addComponent","checkDestroyed","removeApp","deleteApp","_getService","_DEFAULT_ENTRY_NAME","getComponent","instantiationMode","_removeServiceInstance","clearInstance","_addOrOverwriteComponent","firebase$1","createFirebaseNamespace","firebaseAppImpl","apps","__esModule","initializeApp","rawConfig","modularAPIs","appCompat","setLogLevel","onLog","componentName","componentNameWithoutCompat","serviceNamespace","appArg","serviceProps","multipleInstances","useAsService","createFirebaseNamespaceCore","extendNamespace","props","sdkVersion","PlatformLoggerServiceImpl","getPlatformInfoString","getProviders","isVersionServiceProvider","library","logString","DEFAULT_ENTRY_NAME","PLATFORM_LOG_STRING","name$o","_apps","_components","addComponent","debug","addOrOverwriteComponent","heartbeatController","triggerHeartbeat","_clearComponents","_isDeleted","_options","_config","_name","_automaticDataCollectionEnabled","_container","isDeleted","existingApp","newApp","getApps","libraryKeyOrName","libraryMismatch","versionMismatch","warning","logCallback","setUserLogHandler","setLogLevel$1","getDbPromise","openDB","upgrade","writeHeartbeatsToIndexedDB","heartbeatObject","tx","done","idbGetError","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","agent","date","getUTCDateString","lastSentHeartbeatDate","heartbeats","some","singleDateHeartbeat","hbTimestamp","valueOf","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","hb","dates","countBytes","extractHeartbeatsForHeader","headerString","toISOString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","version$1","instanceFactory","onInstanceCreated","mode","instances","instancesDeferred","instancesOptions","onInitCallbacks","normalizedIdentifier","normalizeInstanceIdentifier","shouldAutoInitialize","getOrInitializeService","isComponentEager","instanceDeferred","services","isComponentSet","opts","existingCallbacks","invokeOnInitCallbacks","providers","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","_logLevel","_logHandler","_userLogHandler","TypeError","logHandler","userLogHandler","level","inst","customLogLevel","ignored","UploadTaskSnapshotCompat","UploadTaskCompat","wrappedNextOrObserver","taskSnapshot","ListResultCompat","ReferenceCompat","putString","_dataFromString","_UploadTask","_FbsBlob","_invalidRootOperation","StorageServiceCompat","isUrl","_invalidArgument","_Location","setMaxUploadRetryTime","setMaxOperationRetryTime","storageExp","namespaceExports","_TaskState","_TaskEvent","Storage","registerStorage"],"sourceRoot":""}