.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, /*persistenceKey=*/'', /*includeNamespaceInQueryParams=*/namespace !== parsedUrl.subdomain),\n path: new Path(parsedUrl.pathString)\n };\n};\nconst parseDatabaseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\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 // 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(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\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 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 return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\nconst 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 // 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 = [];\n return function (now) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\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 let id = timeStampChars.join('');\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 return id;\n };\n}();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * Encapsulates the data needed to raise an event\r\n */\nclass DataEvent {\n /**\r\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param eventRegistration - The function to call to with the event data. User provided\r\n * @param snapshot - The data backing the event\r\n * @param prevName - Optional, the name of the previous child for child_* events.\r\n */\n constructor(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n getPath() {\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() {\n return this.eventType;\n }\n getEventRunner() {\n return this.eventRegistration.getEventRunner(this);\n }\n toString() {\n return this.getPath().toString() + ':' + this.eventType + ':' + stringify(this.snapshot.exportVal());\n }\n}\nclass CancelEvent {\n constructor(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n getPath() {\n return this.path;\n }\n getEventType() {\n return 'cancel';\n }\n getEventRunner() {\n return this.eventRegistration.getEventRunner(this);\n }\n toString() {\n return this.path.toString() + ':cancel';\n }\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * A wrapper class that converts events from the database@exp SDK to the legacy\r\n * Database SDK. Events are not converted directly as event registration relies\r\n * on reference comparison of the original user callback (see `matches()`) and\r\n * relies on equality of the legacy SDK's `context` object.\r\n */\nclass CallbackContext {\n constructor(snapshotCallback, cancelCallback) {\n this.snapshotCallback = snapshotCallback;\n this.cancelCallback = cancelCallback;\n }\n onValue(expDataSnapshot, previousChildName) {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n onCancel(error) {\n assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\n return this.cancelCallback.call(null, error);\n }\n get hasCancelCallback() {\n return !!this.cancelCallback;\n }\n matches(other) {\n return this.snapshotCallback === other.snapshotCallback || this.snapshotCallback.userCallback !== undefined && this.snapshotCallback.userCallback === other.snapshotCallback.userCallback && this.snapshotCallback.context === other.snapshotCallback.context;\n }\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * The `onDisconnect` class allows you to write or clear data when your client\r\n * disconnects from the Database server. These updates occur whether your\r\n * client disconnects cleanly or not, so you can rely on them to clean up data\r\n * even if a connection is dropped or a client crashes.\r\n *\r\n * The `onDisconnect` class is most commonly used to manage presence in\r\n * applications where it is useful to detect how many clients are connected and\r\n * when other clients disconnect. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * To avoid problems when a connection is dropped before the requests can be\r\n * transferred to the Database server, these functions should be called before\r\n * writing any data.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time you reconnect.\r\n */\nclass OnDisconnect {\n /** @hideconstructor */\n constructor(_repo, _path) {\n this._repo = _repo;\n this._path = _path;\n }\n /**\r\n * Cancels all previously queued `onDisconnect()` set or update events for this\r\n * location and all children.\r\n *\r\n * If a write has been queued for this location via a `set()` or `update()` at a\r\n * parent location, the write at this location will be canceled, though writes\r\n * to sibling locations will still occur.\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\n cancel() {\n const deferred = new Deferred();\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => {}));\n return deferred.promise;\n }\n /**\r\n * Ensures the data at this location is deleted when the client is disconnected\r\n * (due to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\n remove() {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => {}));\n return deferred.promise;\n }\n /**\r\n * Ensures the data at this location is set to the specified value when the\r\n * client is disconnected (due to closing the browser, navigating to a new page,\r\n * or network issues).\r\n *\r\n * `set()` is especially useful for implementing \"presence\" systems, where a\r\n * value should be changed or cleared when a user disconnects so that they\r\n * appear \"offline\" to other users. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time.\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\n set(value) {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => {}));\n return deferred.promise;\n }\n /**\r\n * Ensures the data at this location is set to the specified value and priority\r\n * when the client is disconnected (due to closing the browser, navigating to a\r\n * new page, or network issues).\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\n setWithPriority(value, priority) {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n const deferred = new Deferred();\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => {}));\n return deferred.promise;\n }\n /**\r\n * Writes multiple values at this location when the client is disconnected (due\r\n * to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\r\n * from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\n update(values) {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => {}));\n return deferred.promise;\n }\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @internal\r\n */\nclass QueryImpl {\n /**\r\n * @hideconstructor\r\n */\n constructor(_repo, _path, _queryParams, _orderByCalled) {\n this._repo = _repo;\n this._path = _path;\n this._queryParams = _queryParams;\n this._orderByCalled = _orderByCalled;\n }\n get key() {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n get ref() {\n return new ReferenceImpl(this._repo, this._path);\n }\n get _queryIdentifier() {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n /**\r\n * An object representation of the query parameters used by this Query.\r\n */\n get _queryObject() {\n return queryParamsGetQueryObject(this._queryParams);\n }\n isEqual(other) {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\n return sameRepo && samePath && sameQueryIdentifier;\n }\n toJSON() {\n return this.toString();\n }\n toString() {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n/**\r\n * Validates that no other order by call has been made\r\n */\nfunction validateNoPreviousOrderByCall(query, fnName) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n/**\r\n * Validates start/end values for queries.\r\n */\nfunction validateQueryEndpoints(params) {\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 if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + '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 (startNode != null && !isValidPriority(startNode) || endNode != null && !isValidPriority(endNode)) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + '(null, a number, or a string).');\n }\n } else {\n assert(params.getIndex() instanceof PathIndex || params.getIndex() === VALUE_INDEX, 'unknown index type.');\n if (startNode != null && typeof startNode === 'object' || endNode != null && typeof endNode === 'object') {\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + 'equalTo() cannot be an object.');\n }\n }\n}\n/**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n */\nfunction validateLimit(params) {\n if (params.hasStart() && params.hasEnd() && params.hasLimit() && !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" + 'limitToFirst() or limitToLast() instead.');\n }\n}\n/**\r\n * @internal\r\n */\nclass ReferenceImpl extends QueryImpl {\n /** @hideconstructor */\n constructor(repo, path) {\n super(repo, path, new QueryParams(), false);\n }\n get parent() {\n const parentPath = pathParent(this._path);\n return parentPath === null ? null : new ReferenceImpl(this._repo, parentPath);\n }\n get root() {\n let ref = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n/**\r\n * A `DataSnapshot` contains data from a Database location.\r\n *\r\n * Any time you read data from the Database, you receive the data as a\r\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\r\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\r\n * JavaScript object by calling the `val()` method. Alternatively, you can\r\n * traverse into the snapshot by calling `child()` to return child snapshots\r\n * (which you could then call `val()` on).\r\n *\r\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\r\n * a Database location. It cannot be modified and will never change (to modify\r\n * data, you always call the `set()` method on a `Reference` directly).\r\n */\nclass DataSnapshot {\n /**\r\n * @param _node - A SnapshotNode to wrap.\r\n * @param ref - The location this snapshot came from.\r\n * @param _index - The iteration order for this snapshot\r\n * @hideconstructor\r\n */\n constructor(_node,\n /**\r\n * The location of this DataSnapshot.\r\n */\n ref, _index) {\n this._node = _node;\n this.ref = ref;\n this._index = _index;\n }\n /**\r\n * Gets the priority value of the data in this `DataSnapshot`.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\r\n * ).\r\n */\n get priority() {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val();\n }\n /**\r\n * The key (last part of the path) of the location of this `DataSnapshot`.\r\n *\r\n * The last token in a Database location is considered its key. For example,\r\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\r\n * `DataSnapshot` will return the key for the location that generated it.\r\n * However, accessing the key on the root URL of a Database will return\r\n * `null`.\r\n */\n get key() {\n return this.ref.key;\n }\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size() {\n return this._node.numChildren();\n }\n /**\r\n * Gets another `DataSnapshot` for the location at the specified relative path.\r\n *\r\n * Passing a relative path to the `child()` method of a DataSnapshot returns\r\n * another `DataSnapshot` for the location at the specified relative path. The\r\n * relative path can either be a simple child name (for example, \"ada\") or a\r\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\r\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\r\n * whose value is `null`) is returned.\r\n *\r\n * @param path - A relative path to the location of child data.\r\n */\n child(path) {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\n }\n /**\r\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\r\n * efficient than using `snapshot.val() !== null`.\r\n */\n exists() {\n return !this._node.isEmpty();\n }\n /**\r\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\r\n *\r\n * The `exportVal()` method is similar to `val()`, except priority information\r\n * is included (if available), making it suitable for backing up your data.\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal() {\n return this._node.val(true);\n }\n /**\r\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\r\n *\r\n * Because of the way JavaScript objects work, the ordering of data in the\r\n * JavaScript object returned by `val()` is not guaranteed to match the\r\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\r\n * where `forEach()` comes in handy. It guarantees the children of a\r\n * `DataSnapshot` will be iterated in their query order.\r\n *\r\n * If no explicit `orderBy*()` method is used, results are returned\r\n * ordered by key (unless priorities are used, in which case, results are\r\n * returned by priority).\r\n *\r\n * @param action - A function that will be called for each child DataSnapshot.\r\n * The callback can return true to cancel further enumeration.\r\n * @returns true if enumeration was canceled due to your callback returning\r\n * true.\r\n */\n forEach(action) {\n if (this._node.isLeafNode()) {\n return false;\n }\n const childrenNode = this._node;\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(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\n });\n }\n /**\r\n * Returns true if the specified child path has (non-null) data.\r\n *\r\n * @param path - A relative path to the location of a potential child.\r\n * @returns `true` if data exists at the specified child path; else\r\n * `false`.\r\n */\n hasChild(path) {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n /**\r\n * Returns whether or not the `DataSnapshot` has any non-`null` child\r\n * properties.\r\n *\r\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\r\n * children. If it does, you can enumerate them using `forEach()`. If it\r\n * doesn't, then either this snapshot contains a primitive value (which can be\r\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\r\n * `null`).\r\n *\r\n * @returns true if this snapshot has any children; else false.\r\n */\n hasChildren() {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n */\n toJSON() {\n return this.exportVal();\n }\n /**\r\n * Extracts a JavaScript value from a `DataSnapshot`.\r\n *\r\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\r\n * scalar type (string, number, or boolean), an array, or an object. It may\r\n * also return null, indicating that the `DataSnapshot` is empty (contains no\r\n * data).\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val() {\n return this._node.val();\n }\n}\n/**\r\n *\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided path. If no path is provided, the `Reference`\r\n * will point to the root of the Database.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param path - Optional path representing the location the returned\r\n * `Reference` will point. If not provided, the returned `Reference` will\r\n * point to the root of the Database.\r\n * @returns If a path is provided, a `Reference`\r\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\r\n * root of the Database.\r\n */\nfunction ref(db, path) {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n/**\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided Firebase URL.\r\n *\r\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\r\n * has a different domain than the current `Database` instance.\r\n *\r\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\r\n * and are not applied to the returned `Reference`.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param url - The Firebase URL at which the returned `Reference` will\r\n * point.\r\n * @returns A `Reference` pointing to the provided\r\n * Firebase URL.\r\n */\nfunction refFromURL(db, url) {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n const repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() && repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' + ': Host name does not match the current database: ' + '(found ' + repoInfo.host + ' but expected ' + db._repo.repoInfo_.host + ')');\n }\n return ref(db, parsedURL.path.toString());\n}\n/**\r\n * Gets a `Reference` for the location at the specified relative path.\r\n *\r\n * The relative path can either be a simple child name (for example, \"ada\") or\r\n * a deeper slash-separated path (for example, \"ada/name/first\").\r\n *\r\n * @param parent - The parent location.\r\n * @param path - A relative path from this location to the desired child\r\n * location.\r\n * @returns The specified child location.\r\n */\nfunction child(parent, path) {\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/**\r\n * Returns an `OnDisconnect` object - see\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information on how to use it.\r\n *\r\n * @param ref - The reference to add OnDisconnect triggers for.\r\n */\nfunction onDisconnect(ref) {\n ref = getModularInstance(ref);\n return new OnDisconnect(ref._repo, ref._path);\n}\n/**\r\n * Generates a new child location using a unique key and returns its\r\n * `Reference`.\r\n *\r\n * This is the most common pattern for adding data to a collection of items.\r\n *\r\n * If you provide a value to `push()`, the value is written to the\r\n * generated location. If you don't pass a value, nothing is written to the\r\n * database and the child remains empty (but you can use the `Reference`\r\n * elsewhere).\r\n *\r\n * The unique keys generated by `push()` are ordered by the current time, so the\r\n * resulting list of items is chronologically sorted. The keys are also\r\n * designed to be unguessable (they contain 72 random bits of entropy).\r\n *\r\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}.\r\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}.\r\n *\r\n * @param parent - The parent location.\r\n * @param value - Optional value to be written at the generated location.\r\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\r\n * but can be used immediately as the `Reference` to the child location.\r\n */\nfunction push(parent, value) {\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 // 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 thenablePushRef = child(parent, name);\n const pushRef = child(parent, name);\n let promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef;\n}\n/**\r\n * Removes the data at this Database location.\r\n *\r\n * Any data at child locations will also be deleted.\r\n *\r\n * The effect of the remove will be visible immediately and the corresponding\r\n * event 'value' will be triggered. Synchronization of the remove to the\r\n * Firebase servers will also be started, and the returned Promise will resolve\r\n * when complete. If provided, the onComplete callback will be called\r\n * asynchronously after synchronization has finished.\r\n *\r\n * @param ref - The location to remove.\r\n * @returns Resolves when remove on server is complete.\r\n */\nfunction remove(ref) {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n/**\r\n * Writes data to this Database location.\r\n *\r\n * This will overwrite any data at this location and all child locations.\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\r\n * all data at this location and all child locations will be deleted.\r\n *\r\n * `set()` will remove any priority stored at this location, so if priority is\r\n * meant to be preserved, you need to use `setWithPriority()` instead.\r\n *\r\n * Note that modifying data with `set()` will cancel any pending transactions\r\n * at that location, so extreme care should be taken if mixing `set()` and\r\n * `transaction()` to modify the same data.\r\n *\r\n * A single `set()` will generate a single \"value\" event at the location where\r\n * the `set()` was performed.\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\nfunction set(ref, value) {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\n repoSetWithPriority(ref._repo, ref._path, value, /*priority=*/null, deferred.wrapCallback(() => {}));\n return deferred.promise;\n}\n/**\r\n * Sets a priority for the data at this Database location.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\nfunction setPriority(ref, priority) {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => {}));\n return deferred.promise;\n}\n/**\r\n * Writes data the Database location. Like `set()` but also specifies the\r\n * priority for that data.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\nfunction setWithPriority(ref, value, priority) {\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 const deferred = new Deferred();\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => {}));\n return deferred.promise;\n}\n/**\r\n * Writes multiple values to the Database at once.\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example,\r\n * \"name/first\") from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * A single `update()` will generate a single \"value\" event at the location\r\n * where the `update()` was performed, regardless of how many children were\r\n * modified.\r\n *\r\n * Note that modifying data with `update()` will cancel any pending\r\n * transactions at that location, so extreme care should be taken if mixing\r\n * `update()` and `transaction()` to modify the same data.\r\n *\r\n * Passing `null` to `update()` will remove the data at this location.\r\n *\r\n * See\r\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\r\n *\r\n * @param ref - The location to write to.\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when update on server is complete.\r\n */\nfunction update(ref, values) {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => {}));\n return deferred.promise;\n}\n/**\r\n * Gets the most up-to-date result for this query.\r\n *\r\n * @param query - The query to run.\r\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\r\n * available, or rejects if the client is unable to return a value (e.g., if the\r\n * server is unreachable and there is nothing cached).\r\n */\nfunction get(query) {\n query = getModularInstance(query);\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\n });\n}\n/**\r\n * Represents registration for 'value' events.\r\n */\nclass ValueEventRegistration {\n constructor(callbackContext) {\n this.callbackContext = callbackContext;\n }\n respondsTo(eventType) {\n return eventType === 'value';\n }\n createEvent(change, query) {\n const index = query._queryParams.getIndex();\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\n }\n getEventRunner(eventData) {\n if (eventData.getEventType() === 'cancel') {\n return () => this.callbackContext.onCancel(eventData.error);\n } else {\n return () => this.callbackContext.onValue(eventData.snapshot, null);\n }\n }\n createCancelEvent(error, path) {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n matches(other) {\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 hasAnyCallback() {\n return this.callbackContext !== null;\n }\n}\n/**\r\n * Represents the registration of a child_x event.\r\n */\nclass ChildEventRegistration {\n constructor(eventType, callbackContext) {\n this.eventType = eventType;\n this.callbackContext = callbackContext;\n }\n respondsTo(eventType) {\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck = eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n createCancelEvent(error, path) {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n createEvent(change, query) {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\n const index = query._queryParams.getIndex();\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\n }\n getEventRunner(eventData) {\n if (eventData.getEventType() === 'cancel') {\n return () => this.callbackContext.onCancel(eventData.error);\n } else {\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\n }\n }\n matches(other) {\n if (other instanceof ChildEventRegistration) {\n return this.eventType === other.eventType && (!this.callbackContext || !other.callbackContext || this.callbackContext.matches(other.callbackContext));\n }\n return false;\n }\n hasAnyCallback() {\n return !!this.callbackContext;\n }\n}\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\n let cancelCallback;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback = (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 const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\n const container = eventType === 'value' ? new ValueEventRegistration(callbackContext) : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\n}\n/**\r\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\r\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\r\n * the respective `on*` callbacks.\r\n *\r\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\r\n * will not automatically remove listeners registered on child nodes, `off()`\r\n * must also be called on any child listeners to remove the callback.\r\n *\r\n * If a callback is not specified, all callbacks for the specified eventType\r\n * will be removed. Similarly, if no eventType is specified, all callbacks\r\n * for the `Reference` will be removed.\r\n *\r\n * Individual listeners can also be removed by invoking their unsubscribe\r\n * callbacks.\r\n *\r\n * @param query - The query that the listener was registered with.\r\n * @param eventType - One of the following strings: \"value\", \"child_added\",\r\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\r\n * for the `Reference` will be removed.\r\n * @param callback - The callback function that was passed to `on()` or\r\n * `undefined` to remove all callbacks.\r\n */\nfunction off(query, eventType, callback) {\n let container = 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/**\r\n * A `QueryConstraint` is used to narrow the set of documents returned by a\r\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\r\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\r\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\r\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\r\n * {@link orderByValue} or {@link equalTo} and\r\n * can then be passed to {@link query} to create a new query instance that\r\n * also contains this `QueryConstraint`.\r\n */\nclass QueryConstraint {}\nclass QueryEndAtConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'endAt';\n }\n _apply(query) {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' + 'endBefore or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\r\n * Creates a `QueryConstraint` with the specified ending point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name less than or equal\r\n * to the specified key.\r\n *\r\n * You can read more about `endAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to end at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end at, among the children with the previously\r\n * specified priority. This argument is only allowed if ordering by child,\r\n * value, or priority.\r\n */\nfunction endAt(value, key) {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\nclass QueryEndBeforeConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'endBefore';\n }\n _apply(query) {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + 'endBefore or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\r\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is exclusive. If only a value is provided, children\r\n * with a value less than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value less than or equal\r\n * to the specified value and a key name less than the specified key.\r\n *\r\n * @param value - The value to end before. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end before, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\nfunction endBefore(value, key) {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\nclass QueryStartAtConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'startAt';\n }\n _apply(query) {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' + 'startBefore or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\r\n * Creates a `QueryConstraint` with the specified starting point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name greater than or\r\n * equal to the specified key.\r\n *\r\n * You can read more about `startAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to start at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\nfunction startAt(value = null, key) {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\nclass QueryStartAfterConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'startAfter';\n }\n _apply(query) {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + 'startAfter, or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\r\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is exclusive. If only a value is provided, children\r\n * with a value greater than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value greater than or equal\r\n * to the specified value and a a key name greater than the specified key.\r\n *\r\n * @param value - The value to start after. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start after. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\nfunction startAfter(value, key) {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n constructor(_limit) {\n super();\n this._limit = _limit;\n this.type = 'limitToFirst';\n }\n _apply(query) {\n if (query._queryParams.hasLimit()) {\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + 'or limitToLast).');\n }\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\n }\n}\n/**\r\n * Creates a new `QueryConstraint` that if limited to the first specific number\r\n * of children.\r\n *\r\n * The `limitToFirst()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the first 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToFirst()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\nfunction limitToFirst(limit) {\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}\nclass QueryLimitToLastConstraint extends QueryConstraint {\n constructor(_limit) {\n super();\n this._limit = _limit;\n this.type = 'limitToLast';\n }\n _apply(query) {\n if (query._queryParams.hasLimit()) {\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + 'or limitToLast).');\n }\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\n }\n}\n/**\r\n * Creates a new `QueryConstraint` that is limited to return only the last\r\n * specified number of children.\r\n *\r\n * The `limitToLast()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the last 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToLast()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\nfunction limitToLast(limit) {\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 return new QueryLimitToLastConstraint(limit);\n}\nclass QueryOrderByChildConstraint extends QueryConstraint {\n constructor(_path) {\n super();\n this._path = _path;\n this.type = 'orderByChild';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, /*orderByCalled=*/true);\n }\n}\n/**\r\n * Creates a new `QueryConstraint` that orders by the specified child key.\r\n *\r\n * Queries can only order by one key at a time. Calling `orderByChild()`\r\n * multiple times on the same query is an error.\r\n *\r\n * Firebase queries allow you to order your data by any child key on the fly.\r\n * However, if you know in advance what your indexes will be, you can define\r\n * them via the .indexOn rule in your Security Rules for better performance. See\r\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\r\n * rule for more information.\r\n *\r\n * You can read more about `orderByChild()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n *\r\n * @param path - The path to order by.\r\n */\nfunction orderByChild(path) {\n if (path === '$key') {\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\n } else if (path === '$priority') {\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\n } else if (path === '$value') {\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n constructor() {\n super(...arguments);\n this.type = 'orderByKey';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, /*orderByCalled=*/true);\n }\n}\n/**\r\n * Creates a new `QueryConstraint` that orders by the key.\r\n *\r\n * Sorts the results of a query by their (ascending) key values.\r\n *\r\n * You can read more about `orderByKey()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\nfunction orderByKey() {\n return new QueryOrderByKeyConstraint();\n}\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n constructor() {\n super(...arguments);\n this.type = 'orderByPriority';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, /*orderByCalled=*/true);\n }\n}\n/**\r\n * Creates a new `QueryConstraint` that orders by priority.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\r\n * for alternatives to priority.\r\n */\nfunction orderByPriority() {\n return new QueryOrderByPriorityConstraint();\n}\nclass QueryOrderByValueConstraint extends QueryConstraint {\n constructor() {\n super(...arguments);\n this.type = 'orderByValue';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, /*orderByCalled=*/true);\n }\n}\n/**\r\n * Creates a new `QueryConstraint` that orders by value.\r\n *\r\n * If the children of a query are all scalar values (string, number, or\r\n * boolean), you can order the results by their (ascending) values.\r\n *\r\n * You can read more about `orderByValue()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\nfunction orderByValue() {\n return new QueryOrderByValueConstraint();\n}\nclass QueryEqualToValueConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'equalTo';\n }\n _apply(query) {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + 'equalTo).');\n }\n if (query._queryParams.hasEnd()) {\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + 'equalTo).');\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\n }\n}\n/**\r\n * Creates a `QueryConstraint` that includes children that match the specified\r\n * value.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The optional key argument can be used to further limit the range of the\r\n * query. If it is specified, then children that have exactly the specified\r\n * value must also have exactly the specified key as their key name. This can be\r\n * used to filter result sets with many matches for the same value.\r\n *\r\n * You can read more about `equalTo()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to match for. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\nfunction equalTo(value, key) {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n/**\r\n * Creates a new immutable instance of `Query` that is extended to also include\r\n * additional query constraints.\r\n *\r\n * @param query - The Query instance to use as a base for the new constraints.\r\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\r\n * @throws if any of the provided query constraints cannot be combined with the\r\n * existing or new constraints.\r\n */\nfunction query(query, ...queryConstraints) {\n let queryImpl = getModularInstance(query);\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * This variable is also defined in the firebase Node.js Admin SDK. Before\r\n * modifying this definition, consult the definition in:\r\n *\r\n * https://github.com/firebase/firebase-admin-node\r\n *\r\n * and make sure the two are consistent.\r\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n/**\r\n * Creates and caches `Repo` instances.\r\n */\nconst repos = {};\n/**\r\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\r\n */\nlet useRestClient = false;\n/**\r\n * Update an existing `Repo` in place to point to a new host/port.\r\n */\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\n repo.repoInfo_ = new RepoInfo(`${host}:${port}`, /* secure= */false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, /*isUsingEmulator=*/true);\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n/**\r\n * This function should only ever be called to CREATE a new database instance.\r\n * @internal\r\n */\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\n let dbUrl = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" + ' a Project ID when calling firebase.initializeApp().');\n }\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n let isEmulator;\n let dbEmulatorHost = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\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 const authTokenProvider = nodeAdmin && isEmulator ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal('Database URL must point to the root of a Firebase Database ' + '(not including a child path).');\n }\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\n return new Database(repo, app);\n}\n/**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n */\nfunction repoManagerDeleteRepo(repo, appName) {\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/**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param repoInfo - The metadata about the Repo\r\n * @returns The Repo object for the specified server / repoName.\r\n */\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\n let appRepos = repos[app.name];\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n}\n/**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n */\nfunction repoManagerForceRestClient(forceRestClient) {\n useRestClient = forceRestClient;\n}\n/**\r\n * Class representing a Firebase Realtime Database.\r\n */\nclass Database {\n /** @hideconstructor */\n constructor(_repoInternal, /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n app) {\n this._repoInternal = _repoInternal;\n this.app = app;\n /** Represents a `Database` instance. */\n this['type'] = 'database';\n /** Track if the instance has been used (root or repo accessed) */\n this._instanceStarted = false;\n }\n get _repo() {\n if (!this._instanceStarted) {\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n get _root() {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n _delete() {\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 _checkNotDeleted(apiName) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');\n }\n}\n/**\r\n * Force the use of websockets instead of longPolling.\r\n */\nfunction forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n/**\r\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\r\n */\nfunction forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n/**\r\n * Returns the instance of the Realtime Database SDK that is associated with the provided\r\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\r\n * no instance exists or if the existing instance uses a custom database URL.\r\n *\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\r\n * Database instance is associated with.\r\n * @param url - The URL of the Realtime Database instance to connect to. If not\r\n * provided, the SDK connects to the default instance of the Firebase App.\r\n * @returns The `Database` instance of the provided app.\r\n */\nfunction getDatabase(app = getApp(), url) {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n });\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n/**\r\n * Modify the provided instance to communicate with the Realtime Database\r\n * emulator.\r\n *\r\n * Note: This method must be called before performing any other operation.\r\n *\r\n * @param db - The instance to modify.\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 8080)\r\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\r\n */\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n if (db._instanceStarted) {\n fatal('Cannot call useEmulator() after instance has already been initialized.');\n }\n const repo = db._repoInternal;\n let tokenProvider = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal('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 tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token = typeof options.mockUserToken === 'string' ? options.mockUserToken : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\n}\n/**\r\n * Disconnects from the server (all Database operations will be completed\r\n * offline).\r\n *\r\n * The client automatically maintains a persistent connection to the Database\r\n * server, which will remain active indefinitely and reconnect when\r\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\r\n * to control the client connection in cases where a persistent connection is\r\n * undesirable.\r\n *\r\n * While offline, the client will no longer receive data updates from the\r\n * Database. However, all Database operations performed locally will continue to\r\n * immediately fire events, allowing your application to continue behaving\r\n * normally. Additionally, each operation performed locally will automatically\r\n * be queued and retried upon reconnection to the Database server.\r\n *\r\n * To reconnect to the Database and begin receiving remote events, see\r\n * `goOnline()`.\r\n *\r\n * @param db - The instance to disconnect.\r\n */\nfunction goOffline(db) {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n/**\r\n * Reconnects to the server and synchronizes the offline Database state\r\n * with the server state.\r\n *\r\n * This method should be used after disabling the active connection with\r\n * `goOffline()`. Once reconnected, the client will transmit the proper data\r\n * and fire the appropriate events so that your client \"catches up\"\r\n * automatically.\r\n *\r\n * @param db - The instance to reconnect.\r\n */\nfunction goOnline(db) {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\nfunction enableLogging(logger, persistent) {\n enableLogging$1(logger, persistent);\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\nfunction registerDatabase(variant) {\n setSDKVersion(SDK_VERSION$1);\n _registerComponent(new Component('database', (container, {\n instanceIdentifier: url\n }) => {\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(app, authProvider, appCheckProvider, url);\n }, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\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, 'esm2017');\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n/**\r\n * Returns a placeholder value for auto-populating the current timestamp (time\r\n * since the Unix epoch, in milliseconds) as determined by the Firebase\r\n * servers.\r\n */\nfunction serverTimestamp() {\n return SERVER_TIMESTAMP;\n}\n/**\r\n * Returns a placeholder value that can be used to atomically increment the\r\n * current database value by the provided delta.\r\n *\r\n * @param delta - the amount to modify the current value atomically.\r\n * @returns A placeholder value for modifying data atomically server-side.\r\n */\nfunction increment(delta) {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * A type for the resolve value of {@link runTransaction}.\r\n */\nclass TransactionResult {\n /** @hideconstructor */\n constructor(/** Whether the transaction was successfully committed. */\n committed, /** The resulting data snapshot. */\n snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n /** Returns a JSON-serializable representation of this object. */\n toJSON() {\n return {\n committed: this.committed,\n snapshot: this.snapshot.toJSON()\n };\n }\n}\n/**\r\n * Atomically modifies the data at this location.\r\n *\r\n * Atomically modify the data at this location. Unlike a normal `set()`, which\r\n * just overwrites the data regardless of its previous value, `runTransaction()` is\r\n * used to modify the existing value to a new value, ensuring there are no\r\n * conflicts with other clients writing to the same location at the same time.\r\n *\r\n * To accomplish this, you pass `runTransaction()` an update function which is\r\n * used to transform the current value into a new value. If another client\r\n * writes to the location before your new value is successfully written, your\r\n * update function will be called again with the new current value, and the\r\n * write will be retried. This will happen repeatedly until your write succeeds\r\n * without conflict or you abort the transaction by not returning a value from\r\n * your update function.\r\n *\r\n * Note: Modifying data with `set()` will cancel any pending transactions at\r\n * that location, so extreme care should be taken if mixing `set()` and\r\n * `runTransaction()` to update the same data.\r\n *\r\n * Note: When using transactions with Security and Firebase Rules in place, be\r\n * aware that a client needs `.read` access in addition to `.write` access in\r\n * order to perform a transaction. This is because the client-side nature of\r\n * transactions requires the client to read the data in order to transactionally\r\n * update it.\r\n *\r\n * @param ref - The location to atomically modify.\r\n * @param transactionUpdate - A developer-supplied function which will be passed\r\n * the current data stored at this location (as a JavaScript object). The\r\n * function should return the new value it would like written (as a JavaScript\r\n * object). If `undefined` is returned (i.e. you return with no arguments) the\r\n * transaction will be aborted and the data at this location will not be\r\n * modified.\r\n * @param options - An options object to configure transactions.\r\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\r\n * callback to handle success and failure.\r\n */\nfunction runTransaction(ref,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntransactionUpdate, options) {\n var _a;\n ref = getModularInstance(ref);\n validateWritablePath('Reference.transaction', ref._path);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'Reference.transaction failed: ' + ref.key + ' is a read-only object.';\n }\n const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\n const deferred = new Deferred();\n const promiseComplete = (error, committed, node) => {\n let dataSnapshot = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\n return deferred.promise;\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\nPersistentConnection;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', {\n p: pathString\n }, onComplete);\n};\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nPersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', {\n d: data\n }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nConnection;\n/**\r\n * @internal\r\n */\nconst hijackHash = function (newHash) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\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};\nRepoInfo;\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n * @internal\r\n */\nconst forceRestClient = function (forceRestClient) {\n repoManagerForceRestClient(forceRestClient);\n};\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * Used by console to create a database based on the app,\r\n * passed database URL and a custom auth implementation.\r\n * @internal\r\n * @param app - A valid FirebaseApp-like object\r\n * @param url - A valid Firebase databaseURL\r\n * @param version - custom version e.g. firebase-admin version\r\n * @param customAppCheckImpl - custom app check implementation\r\n * @param customAuthImpl - custom auth implementation\r\n */\nfunction _initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n nodeAdmin = false\n}) {\n setSDKVersion(version);\n /**\r\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\r\n * any actual function.\r\n */\n const componentContainer = new ComponentContainer('database-standalone');\n const authProvider = new Provider('auth-internal', componentContainer);\n let appCheckProvider;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider('app-check-internal', componentContainer);\n appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n }\n authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);\n}\n\n/**\r\n * Firebase Realtime Database\r\n *\r\n * @packageDocumentation\r\n */\nregisterDatabase();\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n","import { Observable, merge, of, from } from 'rxjs';\nimport { delay, map, switchMap, scan, distinctUntilChanged, withLatestFrom, skipWhile } from 'rxjs/operators';\nimport { onChildAdded, onChildRemoved, onChildChanged, onChildMoved, onValue, off, get as get$1 } from 'firebase/database';\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 */\nvar _a;\nvar ListenEvent = /*#__PURE__*/function (ListenEvent) {\n ListenEvent[\"added\"] = \"child_added\";\n ListenEvent[\"removed\"] = \"child_removed\";\n ListenEvent[\"changed\"] = \"child_changed\";\n ListenEvent[\"moved\"] = \"child_moved\";\n ListenEvent[\"value\"] = \"value\";\n return ListenEvent;\n}(ListenEvent || {});\nvar ListenerMethods = Object.freeze((_a = {}, _a[ListenEvent.added] = onChildAdded, _a[ListenEvent.removed] = onChildRemoved, _a[ListenEvent.changed] = onChildChanged, _a[ListenEvent.moved] = onChildMoved, _a[ListenEvent.value] = onValue, _a));\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Create an observable from a Database Reference or Database Query.\n * @param ref Database Reference\n * @param event Listen event type ('value', 'added', 'changed', 'removed', 'moved')\n */\nfunction fromRef(ref, event) {\n return new Observable(function (subscriber) {\n var fn = ListenerMethods[event](ref, function (snapshot, prevKey) {\n subscriber.next({\n snapshot: snapshot,\n prevKey: prevKey,\n event: event\n });\n }, subscriber.error.bind(subscriber));\n return {\n unsubscribe: function () {\n off(ref, event, fn);\n }\n };\n }).pipe(\n // Ensures subscribe on observable is async. This handles\n // a quirk in the SDK where on/once callbacks can happen\n // synchronously.\n delay(0));\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\n\nvar __assign = function () {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nfunction __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Check the length of the provided array. If it is empty return an array\n * that is populated with all the Realtime Database child events.\n * @param events\n */\nfunction validateEventsArray(events) {\n if (events == null || events.length === 0) {\n events = [ListenEvent.added, ListenEvent.removed, ListenEvent.changed, ListenEvent.moved];\n }\n return events;\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Get the snapshot changes of an object\n * @param query\n */\nfunction object(query) {\n return fromRef(query, ListenEvent.value);\n}\n/**\n * Get an array of object values, optionally with a mapped key\n * @param query object ref or query\n * @param keyField map the object key to a specific field\n */\nfunction objectVal(query, options) {\n if (options === void 0) {\n options = {};\n }\n return fromRef(query, ListenEvent.value).pipe(map(function (change) {\n return changeToData(change, options);\n }));\n}\nfunction changeToData(change, options) {\n var _a;\n if (options === void 0) {\n options = {};\n }\n var val = change.snapshot.val();\n // match the behavior of the JS SDK when the snapshot doesn't exist\n if (!change.snapshot.exists()) {\n return val;\n }\n // val can be a primitive type\n if (typeof val !== 'object') {\n return val;\n }\n return __assign(__assign({}, val), options.keyField ? (_a = {}, _a[options.keyField] = change.snapshot.key, _a) : null);\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction stateChanges(query, options) {\n if (options === void 0) {\n options = {};\n }\n var events = validateEventsArray(options.events);\n var childEvent$ = events.map(function (event) {\n return fromRef(query, event);\n });\n return merge.apply(void 0, childEvent$);\n}\nfunction get(query) {\n return from(get$1(query)).pipe(map(function (snapshot) {\n var event = ListenEvent.value;\n return {\n snapshot: snapshot,\n prevKey: null,\n event: event\n };\n }));\n}\nfunction list(query, options) {\n if (options === void 0) {\n options = {};\n }\n var events = validateEventsArray(options.events);\n return get(query).pipe(switchMap(function (change) {\n var childEvent$ = [of(change)];\n events.forEach(function (event) {\n childEvent$.push(fromRef(query, event));\n });\n return merge.apply(void 0, childEvent$).pipe(scan(buildView, []));\n }), distinctUntilChanged());\n}\n/**\n * Get an object mapped to its value, and optionally its key\n * @param query object ref or query\n * @param keyField map the object key to a specific field\n */\nfunction listVal(query, options) {\n if (options === void 0) {\n options = {};\n }\n return list(query).pipe(map(function (arr) {\n return arr.map(function (change) {\n return changeToData(change, options);\n });\n }));\n}\nfunction positionFor(changes, key) {\n var len = changes.length;\n for (var i = 0; i < len; i++) {\n if (changes[i].snapshot.key === key) {\n return i;\n }\n }\n return -1;\n}\nfunction positionAfter(changes, prevKey) {\n if (prevKey == null) {\n return 0;\n } else {\n var i = positionFor(changes, prevKey);\n if (i === -1) {\n return changes.length;\n } else {\n return i + 1;\n }\n }\n}\nfunction buildView(current, change) {\n var snapshot = change.snapshot,\n prevKey = change.prevKey,\n event = change.event;\n var key = snapshot.key;\n var currentKeyPosition = positionFor(current, key);\n var afterPreviousKeyPosition = positionAfter(current, prevKey || undefined);\n switch (event) {\n case ListenEvent.value:\n if (change.snapshot && change.snapshot.exists()) {\n var prevKey_1 = null;\n change.snapshot.forEach(function (snapshot) {\n var action = {\n snapshot: snapshot,\n event: ListenEvent.value,\n prevKey: prevKey_1\n };\n prevKey_1 = snapshot.key;\n current = __spreadArray(__spreadArray([], current, true), [action], false);\n return false;\n });\n }\n return current;\n case ListenEvent.added:\n if (currentKeyPosition > -1) {\n // check that the previouskey is what we expect, else reorder\n var previous = current[currentKeyPosition - 1];\n if ((previous && previous.snapshot.key || null) !== prevKey) {\n current = current.filter(function (x) {\n return x.snapshot.key !== snapshot.key;\n });\n current.splice(afterPreviousKeyPosition, 0, change);\n }\n } else if (prevKey == null) {\n return __spreadArray([change], current, true);\n } else {\n current = current.slice();\n current.splice(afterPreviousKeyPosition, 0, change);\n }\n return current;\n case ListenEvent.removed:\n return current.filter(function (x) {\n return x.snapshot.key !== snapshot.key;\n });\n case ListenEvent.changed:\n return current.map(function (x) {\n return x.snapshot.key === key ? change : x;\n });\n case ListenEvent.moved:\n if (currentKeyPosition > -1) {\n var data = current.splice(currentKeyPosition, 1)[0];\n current = current.slice();\n current.splice(afterPreviousKeyPosition, 0, data);\n return current;\n }\n return current;\n // default will also remove null results\n default:\n return current;\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 */\nfunction auditTrail(query, options) {\n if (options === void 0) {\n options = {};\n }\n var auditTrail$ = stateChanges(query, options).pipe(scan(function (current, changes) {\n return __spreadArray(__spreadArray([], current, true), [changes], false);\n }, []));\n return waitForLoaded(query, auditTrail$);\n}\nfunction loadedData(query) {\n // Create an observable of loaded values to retrieve the\n // known dataset. This will allow us to know what key to\n // emit the \"whole\" array at when listening for child events.\n return fromRef(query, ListenEvent.value).pipe(map(function (data) {\n // Store the last key in the data set\n var lastKeyToLoad;\n // Loop through loaded dataset to find the last key\n data.snapshot.forEach(function (child) {\n lastKeyToLoad = child.key;\n return false;\n });\n // return data set and the current last key loaded\n return {\n data: data,\n lastKeyToLoad: lastKeyToLoad\n };\n }));\n}\nfunction waitForLoaded(query, snap$) {\n var loaded$ = loadedData(query);\n return loaded$.pipe(withLatestFrom(snap$),\n // Get the latest values from the \"loaded\" and \"child\" datasets\n // We can use both datasets to form an array of the latest values.\n map(function (_a) {\n var loaded = _a[0],\n changes = _a[1];\n // Store the last key in the data set\n var lastKeyToLoad = loaded.lastKeyToLoad;\n // Store all child keys loaded at this point\n var loadedKeys = changes.map(function (change) {\n return change.snapshot.key;\n });\n return {\n changes: changes,\n lastKeyToLoad: lastKeyToLoad,\n loadedKeys: loadedKeys\n };\n }),\n // This is the magical part, only emit when the last load key\n // in the dataset has been loaded by a child event. At this point\n // we can assume the dataset is \"whole\".\n skipWhile(function (meta) {\n return meta.loadedKeys.indexOf(meta.lastKeyToLoad) === -1;\n }),\n // Pluck off the meta data because the user only cares\n // to iterate through the snapshots\n map(function (meta) {\n return meta.changes;\n }));\n}\nexport { ListenEvent, ListenerMethods, auditTrail, changeToData, fromRef, list, listVal, object, objectVal, stateChanges };\n","import { ɵgetAllInstancesOf as _getAllInstancesOf, ɵgetDefaultInstanceOf as _getDefaultInstanceOf, VERSION, ɵAngularFireSchedulers as _AngularFireSchedulers, ɵAppCheckInstances as _AppCheckInstances, ɵzoneWrap as _zoneWrap } from '@angular/fire';\nimport { timer, from } from 'rxjs';\nimport { concatMap, distinct } from 'rxjs/operators';\nimport * as i0 from '@angular/core';\nimport { InjectionToken, Optional, NgModule, makeEnvironmentProviders, NgZone, Injector } from '@angular/core';\nimport { FirebaseApp, FirebaseApps } from '@angular/fire/app';\nimport { AuthInstances } from '@angular/fire/auth';\nimport { registerVersion } from 'firebase/app';\nimport { fromRef as fromRef$1, stateChanges as stateChanges$1, list as list$1, listVal as listVal$1, auditTrail as auditTrail$1, object as object$1, objectVal as objectVal$1, changeToData as changeToData$1 } from 'rxfire/database';\nexport { ListenEvent, ListenerMethods } from 'rxfire/database';\nimport { child as child$1, connectDatabaseEmulator as connectDatabaseEmulator$1, enableLogging as enableLogging$1, endAt as endAt$1, endBefore as endBefore$1, equalTo as equalTo$1, forceLongPolling as forceLongPolling$1, forceWebSockets as forceWebSockets$1, get as get$1, getDatabase as getDatabase$1, goOffline as goOffline$1, goOnline as goOnline$1, increment as increment$1, limitToFirst as limitToFirst$1, limitToLast as limitToLast$1, off as off$1, onChildAdded as onChildAdded$1, onChildChanged as onChildChanged$1, onChildMoved as onChildMoved$1, onChildRemoved as onChildRemoved$1, onDisconnect as onDisconnect$1, onValue as onValue$1, orderByChild as orderByChild$1, orderByKey as orderByKey$1, orderByPriority as orderByPriority$1, orderByValue as orderByValue$1, push as push$1, query as query$1, ref as ref$1, refFromURL as refFromURL$1, remove as remove$1, runTransaction as runTransaction$1, serverTimestamp as serverTimestamp$1, set as set$1, setPriority as setPriority$1, setWithPriority as setWithPriority$1, startAfter as startAfter$1, startAt as startAt$1, update as update$1 } from 'firebase/database';\nexport * from 'firebase/database';\nclass Database {\n constructor(database) {\n return database;\n }\n}\nconst DATABASE_PROVIDER_NAME = 'database';\nclass DatabaseInstances {\n constructor() {\n return _getAllInstancesOf(DATABASE_PROVIDER_NAME);\n }\n}\nconst databaseInstance$ = /*#__PURE__*/ /*#__PURE__*/timer(0, 300).pipe(/*#__PURE__*/concatMap(() => from(_getAllInstancesOf(DATABASE_PROVIDER_NAME))), /*#__PURE__*/distinct());\nconst PROVIDED_DATABASE_INSTANCES = /*#__PURE__*/new InjectionToken('angularfire2.database-instances');\nfunction defaultDatabaseInstanceFactory(provided, defaultApp) {\n const defaultDatabase = _getDefaultInstanceOf(DATABASE_PROVIDER_NAME, provided, defaultApp);\n return defaultDatabase && new Database(defaultDatabase);\n}\nfunction databaseInstanceFactory(fn) {\n return (zone, injector) => {\n const database = zone.runOutsideAngular(() => fn(injector));\n return new Database(database);\n };\n}\nconst DATABASE_INSTANCES_PROVIDER = {\n provide: DatabaseInstances,\n deps: [[/*#__PURE__*/new Optional(), PROVIDED_DATABASE_INSTANCES]]\n};\nconst DEFAULT_DATABASE_INSTANCE_PROVIDER = {\n provide: Database,\n useFactory: defaultDatabaseInstanceFactory,\n deps: [[/*#__PURE__*/new Optional(), PROVIDED_DATABASE_INSTANCES], FirebaseApp]\n};\nlet DatabaseModule = /*#__PURE__*/(() => {\n class DatabaseModule {\n constructor() {\n registerVersion('angularfire', VERSION.full, 'rtdb');\n }\n static ɵfac = function DatabaseModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || DatabaseModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: DatabaseModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: [DEFAULT_DATABASE_INSTANCE_PROVIDER, DATABASE_INSTANCES_PROVIDER]\n });\n }\n return DatabaseModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction provideDatabase(fn, ...deps) {\n registerVersion('angularfire', VERSION.full, 'rtdb');\n return makeEnvironmentProviders([DEFAULT_DATABASE_INSTANCE_PROVIDER, DATABASE_INSTANCES_PROVIDER, {\n provide: PROVIDED_DATABASE_INSTANCES,\n useFactory: databaseInstanceFactory(fn),\n multi: true,\n deps: [NgZone, Injector, _AngularFireSchedulers, FirebaseApps,\n // Database+Auth work better if Auth is loaded first\n [new Optional(), AuthInstances], [new Optional(), _AppCheckInstances], ...deps]\n }]);\n}\n\n// DO NOT MODIFY, this file is autogenerated by tools/build.ts\nconst fromRef = /*#__PURE__*/_zoneWrap(fromRef$1, true);\nconst stateChanges = /*#__PURE__*/_zoneWrap(stateChanges$1, true);\nconst list = /*#__PURE__*/_zoneWrap(list$1, true);\nconst listVal = /*#__PURE__*/_zoneWrap(listVal$1, true);\nconst auditTrail = /*#__PURE__*/_zoneWrap(auditTrail$1, true);\nconst object = /*#__PURE__*/_zoneWrap(object$1, true);\nconst objectVal = /*#__PURE__*/_zoneWrap(objectVal$1, true);\nconst changeToData = /*#__PURE__*/_zoneWrap(changeToData$1, true);\n\n// DO NOT MODIFY, this file is autogenerated by tools/build.ts\nconst child = /*#__PURE__*/_zoneWrap(child$1, true);\nconst connectDatabaseEmulator = /*#__PURE__*/_zoneWrap(connectDatabaseEmulator$1, true);\nconst enableLogging = /*#__PURE__*/_zoneWrap(enableLogging$1, true);\nconst endAt = /*#__PURE__*/_zoneWrap(endAt$1, true);\nconst endBefore = /*#__PURE__*/_zoneWrap(endBefore$1, true);\nconst equalTo = /*#__PURE__*/_zoneWrap(equalTo$1, true);\nconst forceLongPolling = /*#__PURE__*/_zoneWrap(forceLongPolling$1, true);\nconst forceWebSockets = /*#__PURE__*/_zoneWrap(forceWebSockets$1, true);\nconst get = /*#__PURE__*/_zoneWrap(get$1, true);\nconst getDatabase = /*#__PURE__*/_zoneWrap(getDatabase$1, true);\nconst goOffline = /*#__PURE__*/_zoneWrap(goOffline$1, true);\nconst goOnline = /*#__PURE__*/_zoneWrap(goOnline$1, true);\nconst increment = /*#__PURE__*/_zoneWrap(increment$1, true);\nconst limitToFirst = /*#__PURE__*/_zoneWrap(limitToFirst$1, true);\nconst limitToLast = /*#__PURE__*/_zoneWrap(limitToLast$1, true);\nconst off = /*#__PURE__*/_zoneWrap(off$1, true);\nconst onChildAdded = /*#__PURE__*/_zoneWrap(onChildAdded$1, true);\nconst onChildChanged = /*#__PURE__*/_zoneWrap(onChildChanged$1, true);\nconst onChildMoved = /*#__PURE__*/_zoneWrap(onChildMoved$1, true);\nconst onChildRemoved = /*#__PURE__*/_zoneWrap(onChildRemoved$1, true);\nconst onDisconnect = /*#__PURE__*/_zoneWrap(onDisconnect$1, true);\nconst onValue = /*#__PURE__*/_zoneWrap(onValue$1, true);\nconst orderByChild = /*#__PURE__*/_zoneWrap(orderByChild$1, true);\nconst orderByKey = /*#__PURE__*/_zoneWrap(orderByKey$1, true);\nconst orderByPriority = /*#__PURE__*/_zoneWrap(orderByPriority$1, true);\nconst orderByValue = /*#__PURE__*/_zoneWrap(orderByValue$1, true);\nconst push = /*#__PURE__*/_zoneWrap(push$1, true);\nconst query = /*#__PURE__*/_zoneWrap(query$1, true);\nconst ref = /*#__PURE__*/_zoneWrap(ref$1, true);\nconst refFromURL = /*#__PURE__*/_zoneWrap(refFromURL$1, true);\nconst remove = /*#__PURE__*/_zoneWrap(remove$1, true);\nconst runTransaction = /*#__PURE__*/_zoneWrap(runTransaction$1, true);\nconst serverTimestamp = /*#__PURE__*/_zoneWrap(serverTimestamp$1, true);\nconst set = /*#__PURE__*/_zoneWrap(set$1, true);\nconst setPriority = /*#__PURE__*/_zoneWrap(setPriority$1, true);\nconst setWithPriority = /*#__PURE__*/_zoneWrap(setWithPriority$1, true);\nconst startAfter = /*#__PURE__*/_zoneWrap(startAfter$1, true);\nconst startAt = /*#__PURE__*/_zoneWrap(startAt$1, true);\nconst update = /*#__PURE__*/_zoneWrap(update$1, true);\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { Database, DatabaseInstances, DatabaseModule, auditTrail, changeToData, child, connectDatabaseEmulator, databaseInstance$, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, fromRef, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, list, listVal, object, objectVal, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, provideDatabase, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, stateChanges, update };\n","import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { InternalNavigation } from '../models/internal-navigation';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class MiniLoginService {\n private _currentInternalNavigation: BehaviorSubject = new BehaviorSubject({ page: 'sign-in' });\n constructor() {}\n\n current(internalNavigation: string | InternalNavigation) {\n if (typeof internalNavigation === 'string') this._currentInternalNavigation.next({ page: internalNavigation });\n else this._currentInternalNavigation.next(internalNavigation);\n }\n\n get current$(): Observable {\n return this._currentInternalNavigation.asObservable();\n }\n}\n","import { ElementRef } from '@angular/core';\n\n/** Coerces a data-bound value (typically a string) to a boolean. */\nfunction coerceBooleanProperty(value) {\n return value != null && `${value}` !== 'false';\n}\nfunction coerceNumberProperty(value, fallbackValue = 0) {\n if (_isNumberValue(value)) {\n return Number(value);\n }\n return arguments.length === 2 ? fallbackValue : 0;\n}\n/**\n * Whether the provided value is considered a number.\n * @docs-private\n */\nfunction _isNumberValue(value) {\n // parseFloat(value) handles most of the cases we're interested in (it treats null, empty string,\n // and other non-number values as NaN, where Number just uses 0) but it considers the string\n // '123hello' to be a valid number. Therefore we also check if Number(value) is NaN.\n return !isNaN(parseFloat(value)) && !isNaN(Number(value));\n}\nfunction coerceArray(value) {\n return Array.isArray(value) ? value : [value];\n}\n\n/** Coerces a value to a CSS pixel value. */\nfunction coerceCssPixelValue(value) {\n if (value == null) {\n return '';\n }\n return typeof value === 'string' ? value : `${value}px`;\n}\n\n/**\n * Coerces an ElementRef or an Element into an element.\n * Useful for APIs that can accept either a ref or the native element itself.\n */\nfunction coerceElement(elementOrRef) {\n return elementOrRef instanceof ElementRef ? elementOrRef.nativeElement : elementOrRef;\n}\n\n/**\n * Coerces a value to an array of trimmed non-empty strings.\n * Any input that is not an array, `null` or `undefined` will be turned into a string\n * via `toString()` and subsequently split with the given separator.\n * `null` and `undefined` will result in an empty array.\n * This results in the following outcomes:\n * - `null` -> `[]`\n * - `[null]` -> `[\"null\"]`\n * - `[\"a\", \"b \", \" \"]` -> `[\"a\", \"b\"]`\n * - `[1, [2, 3]]` -> `[\"1\", \"2,3\"]`\n * - `[{ a: 0 }]` -> `[\"[object Object]\"]`\n * - `{ a: 0 }` -> `[\"[object\", \"Object]\"]`\n *\n * Useful for defining CSS classes or table columns.\n * @param value the value to coerce into an array of strings\n * @param separator split-separator if value isn't an array\n */\nfunction coerceStringArray(value, separator = /\\s+/) {\n const result = [];\n if (value != null) {\n const sourceValues = Array.isArray(value) ? value : `${value}`.split(separator);\n for (const sourceValue of sourceValues) {\n const trimmedString = `${sourceValue}`.trim();\n if (trimmedString) {\n result.push(trimmedString);\n }\n }\n }\n return result;\n}\nexport { _isNumberValue, coerceArray, coerceBooleanProperty, coerceCssPixelValue, coerceElement, coerceNumberProperty, coerceStringArray };\n","import * as i0 from '@angular/core';\nimport { inject, PLATFORM_ID, Injectable, NgModule } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n// Whether the current platform supports the V8 Break Iterator. The V8 check\n// is necessary to detect all Blink based browsers.\nlet hasV8BreakIterator;\n// We need a try/catch around the reference to `Intl`, because accessing it in some cases can\n// cause IE to throw. These cases are tied to particular versions of Windows and can happen if\n// the consumer is providing a polyfilled `Map`. See:\n// https://github.com/Microsoft/ChakraCore/issues/3189\n// https://github.com/angular/components/issues/15687\ntry {\n hasV8BreakIterator = typeof Intl !== 'undefined' && Intl.v8BreakIterator;\n} catch {\n hasV8BreakIterator = false;\n}\n/**\n * Service to detect the current platform by comparing the userAgent strings and\n * checking browser-specific global properties.\n */\nlet Platform = /*#__PURE__*/(() => {\n class Platform {\n _platformId = inject(PLATFORM_ID);\n // We want to use the Angular platform check because if the Document is shimmed\n // without the navigator, the following checks will fail. This is preferred because\n // sometimes the Document may be shimmed without the user's knowledge or intention\n /** Whether the Angular application is being rendered in the browser. */\n isBrowser = this._platformId ? isPlatformBrowser(this._platformId) : typeof document === 'object' && !!document;\n /** Whether the current browser is Microsoft Edge. */\n EDGE = this.isBrowser && /(edge)/i.test(navigator.userAgent);\n /** Whether the current rendering engine is Microsoft Trident. */\n TRIDENT = this.isBrowser && /(msie|trident)/i.test(navigator.userAgent);\n // EdgeHTML and Trident mock Blink specific things and need to be excluded from this check.\n /** Whether the current rendering engine is Blink. */\n BLINK = this.isBrowser && !!(window.chrome || hasV8BreakIterator) && typeof CSS !== 'undefined' && !this.EDGE && !this.TRIDENT;\n // Webkit is part of the userAgent in EdgeHTML, Blink and Trident. Therefore we need to\n // ensure that Webkit runs standalone and is not used as another engine's base.\n /** Whether the current rendering engine is WebKit. */\n WEBKIT = this.isBrowser && /AppleWebKit/i.test(navigator.userAgent) && !this.BLINK && !this.EDGE && !this.TRIDENT;\n /** Whether the current platform is Apple iOS. */\n IOS = this.isBrowser && /iPad|iPhone|iPod/.test(navigator.userAgent) && !('MSStream' in window);\n // It's difficult to detect the plain Gecko engine, because most of the browsers identify\n // them self as Gecko-like browsers and modify the userAgent's according to that.\n // Since we only cover one explicit Firefox case, we can simply check for Firefox\n // instead of having an unstable check for Gecko.\n /** Whether the current browser is Firefox. */\n FIREFOX = this.isBrowser && /(firefox|minefield)/i.test(navigator.userAgent);\n /** Whether the current platform is Android. */\n // Trident on mobile adds the android platform to the userAgent to trick detections.\n ANDROID = this.isBrowser && /android/i.test(navigator.userAgent) && !this.TRIDENT;\n // Safari browsers will include the Safari keyword in their userAgent. Some browsers may fake\n // this and just place the Safari keyword in the userAgent. To be more safe about Safari every\n // Safari browser should also use Webkit as its layout engine.\n /** Whether the current browser is Safari. */\n SAFARI = this.isBrowser && /safari/i.test(navigator.userAgent) && this.WEBKIT;\n constructor() {}\n static ɵfac = function Platform_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || Platform)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: Platform,\n factory: Platform.ɵfac,\n providedIn: 'root'\n });\n }\n return Platform;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet PlatformModule = /*#__PURE__*/(() => {\n class PlatformModule {\n static ɵfac = function PlatformModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || PlatformModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: PlatformModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({});\n }\n return PlatformModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Cached result Set of input types support by the current browser. */\nlet supportedInputTypes;\n/** Types of `` that *might* be supported. */\nconst candidateInputTypes = [\n// `color` must come first. Chrome 56 shows a warning if we change the type to `color` after\n// first changing it to something else:\n// The specified value \"\" does not conform to the required format.\n// The format is \"#rrggbb\" where rr, gg, bb are two-digit hexadecimal numbers.\n'color', 'button', 'checkbox', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month', 'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time', 'url', 'week'];\n/** @returns The input types supported by this browser. */\nfunction getSupportedInputTypes() {\n // Result is cached.\n if (supportedInputTypes) {\n return supportedInputTypes;\n }\n // We can't check if an input type is not supported until we're on the browser, so say that\n // everything is supported when not on the browser. We don't use `Platform` here since it's\n // just a helper function and can't inject it.\n if (typeof document !== 'object' || !document) {\n supportedInputTypes = new Set(candidateInputTypes);\n return supportedInputTypes;\n }\n let featureTestInput = document.createElement('input');\n supportedInputTypes = new Set(candidateInputTypes.filter(value => {\n featureTestInput.setAttribute('type', value);\n return featureTestInput.type === value;\n }));\n return supportedInputTypes;\n}\n\n/** Cached result of whether the user's browser supports passive event listeners. */\nlet supportsPassiveEvents;\n/**\n * Checks whether the user's browser supports passive event listeners.\n * See: https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n */\nfunction supportsPassiveEventListeners() {\n if (supportsPassiveEvents == null && typeof window !== 'undefined') {\n try {\n window.addEventListener('test', null, Object.defineProperty({}, 'passive', {\n get: () => supportsPassiveEvents = true\n }));\n } finally {\n supportsPassiveEvents = supportsPassiveEvents || false;\n }\n }\n return supportsPassiveEvents;\n}\n/**\n * Normalizes an `AddEventListener` object to something that can be passed\n * to `addEventListener` on any browser, no matter whether it supports the\n * `options` parameter.\n * @param options Object to be normalized.\n */\nfunction normalizePassiveListenerOptions(options) {\n return supportsPassiveEventListeners() ? options : !!options.capture;\n}\n\n/** The possible ways the browser may handle the horizontal scroll axis in RTL languages. */\nvar RtlScrollAxisType = /*#__PURE__*/function (RtlScrollAxisType) {\n /**\n * scrollLeft is 0 when scrolled all the way left and (scrollWidth - clientWidth) when scrolled\n * all the way right.\n */\n RtlScrollAxisType[RtlScrollAxisType[\"NORMAL\"] = 0] = \"NORMAL\";\n /**\n * scrollLeft is -(scrollWidth - clientWidth) when scrolled all the way left and 0 when scrolled\n * all the way right.\n */\n RtlScrollAxisType[RtlScrollAxisType[\"NEGATED\"] = 1] = \"NEGATED\";\n /**\n * scrollLeft is (scrollWidth - clientWidth) when scrolled all the way left and 0 when scrolled\n * all the way right.\n */\n RtlScrollAxisType[RtlScrollAxisType[\"INVERTED\"] = 2] = \"INVERTED\";\n return RtlScrollAxisType;\n}(RtlScrollAxisType || {});\n/** Cached result of the way the browser handles the horizontal scroll axis in RTL mode. */\nlet rtlScrollAxisType;\n/** Cached result of the check that indicates whether the browser supports scroll behaviors. */\nlet scrollBehaviorSupported;\n/** Check whether the browser supports scroll behaviors. */\nfunction supportsScrollBehavior() {\n if (scrollBehaviorSupported == null) {\n // If we're not in the browser, it can't be supported. Also check for `Element`, because\n // some projects stub out the global `document` during SSR which can throw us off.\n if (typeof document !== 'object' || !document || typeof Element !== 'function' || !Element) {\n scrollBehaviorSupported = false;\n return scrollBehaviorSupported;\n }\n // If the element can have a `scrollBehavior` style, we can be sure that it's supported.\n if ('scrollBehavior' in document.documentElement.style) {\n scrollBehaviorSupported = true;\n } else {\n // At this point we have 3 possibilities: `scrollTo` isn't supported at all, it's\n // supported but it doesn't handle scroll behavior, or it has been polyfilled.\n const scrollToFunction = Element.prototype.scrollTo;\n if (scrollToFunction) {\n // We can detect if the function has been polyfilled by calling `toString` on it. Native\n // functions are obfuscated using `[native code]`, whereas if it was overwritten we'd get\n // the actual function source. Via https://davidwalsh.name/detect-native-function. Consider\n // polyfilled functions as supporting scroll behavior.\n scrollBehaviorSupported = !/\\{\\s*\\[native code\\]\\s*\\}/.test(scrollToFunction.toString());\n } else {\n scrollBehaviorSupported = false;\n }\n }\n }\n return scrollBehaviorSupported;\n}\n/**\n * Checks the type of RTL scroll axis used by this browser. As of time of writing, Chrome is NORMAL,\n * Firefox & Safari are NEGATED, and IE & Edge are INVERTED.\n */\nfunction getRtlScrollAxisType() {\n // We can't check unless we're on the browser. Just assume 'normal' if we're not.\n if (typeof document !== 'object' || !document) {\n return RtlScrollAxisType.NORMAL;\n }\n if (rtlScrollAxisType == null) {\n // Create a 1px wide scrolling container and a 2px wide content element.\n const scrollContainer = document.createElement('div');\n const containerStyle = scrollContainer.style;\n scrollContainer.dir = 'rtl';\n containerStyle.width = '1px';\n containerStyle.overflow = 'auto';\n containerStyle.visibility = 'hidden';\n containerStyle.pointerEvents = 'none';\n containerStyle.position = 'absolute';\n const content = document.createElement('div');\n const contentStyle = content.style;\n contentStyle.width = '2px';\n contentStyle.height = '1px';\n scrollContainer.appendChild(content);\n document.body.appendChild(scrollContainer);\n rtlScrollAxisType = RtlScrollAxisType.NORMAL;\n // The viewport starts scrolled all the way to the right in RTL mode. If we are in a NORMAL\n // browser this would mean that the scrollLeft should be 1. If it's zero instead we know we're\n // dealing with one of the other two types of browsers.\n if (scrollContainer.scrollLeft === 0) {\n // In a NEGATED browser the scrollLeft is always somewhere in [-maxScrollAmount, 0]. For an\n // INVERTED browser it is always somewhere in [0, maxScrollAmount]. We can determine which by\n // setting to the scrollLeft to 1. This is past the max for a NEGATED browser, so it will\n // return 0 when we read it again.\n scrollContainer.scrollLeft = 1;\n rtlScrollAxisType = scrollContainer.scrollLeft === 0 ? RtlScrollAxisType.NEGATED : RtlScrollAxisType.INVERTED;\n }\n scrollContainer.remove();\n }\n return rtlScrollAxisType;\n}\nlet shadowDomIsSupported;\n/** Checks whether the user's browser support Shadow DOM. */\nfunction _supportsShadowDom() {\n if (shadowDomIsSupported == null) {\n const head = typeof document !== 'undefined' ? document.head : null;\n shadowDomIsSupported = !!(head && (head.createShadowRoot || head.attachShadow));\n }\n return shadowDomIsSupported;\n}\n/** Gets the shadow root of an element, if supported and the element is inside the Shadow DOM. */\nfunction _getShadowRoot(element) {\n if (_supportsShadowDom()) {\n const rootNode = element.getRootNode ? element.getRootNode() : null;\n // Note that this should be caught by `_supportsShadowDom`, but some\n // teams have been able to hit this code path on unsupported browsers.\n if (typeof ShadowRoot !== 'undefined' && ShadowRoot && rootNode instanceof ShadowRoot) {\n return rootNode;\n }\n }\n return null;\n}\n/**\n * Gets the currently-focused element on the page while\n * also piercing through Shadow DOM boundaries.\n */\nfunction _getFocusedElementPierceShadowDom() {\n let activeElement = typeof document !== 'undefined' && document ? document.activeElement : null;\n while (activeElement && activeElement.shadowRoot) {\n const newActiveElement = activeElement.shadowRoot.activeElement;\n if (newActiveElement === activeElement) {\n break;\n } else {\n activeElement = newActiveElement;\n }\n }\n return activeElement;\n}\n/** Gets the target of an event while accounting for Shadow DOM. */\nfunction _getEventTarget(event) {\n // If an event is bound outside the Shadow DOM, the `event.target` will\n // point to the shadow root so we have to use `composedPath` instead.\n return event.composedPath ? event.composedPath()[0] : event.target;\n}\n\n/** Gets whether the code is currently running in a test environment. */\nfunction _isTestEnvironment() {\n // We can't use `declare const` because it causes conflicts inside Google with the real typings\n // for these symbols and we can't read them off the global object, because they don't appear to\n // be attached there for some runners like Jest.\n // (see: https://github.com/angular/components/issues/23365#issuecomment-938146643)\n return (\n // @ts-ignore\n typeof __karma__ !== 'undefined' && !!__karma__ ||\n // @ts-ignore\n typeof jasmine !== 'undefined' && !!jasmine ||\n // @ts-ignore\n typeof jest !== 'undefined' && !!jest ||\n // @ts-ignore\n typeof Mocha !== 'undefined' && !!Mocha\n );\n}\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { Platform, PlatformModule, RtlScrollAxisType, _getEventTarget, _getFocusedElementPierceShadowDom, _getShadowRoot, _isTestEnvironment, _supportsShadowDom, getRtlScrollAxisType, getSupportedInputTypes, normalizePassiveListenerOptions, supportsPassiveEventListeners, supportsScrollBehavior };\n","import * as i0 from '@angular/core';\nimport { inject, Injector, EnvironmentInjector, ApplicationRef, createComponent, Injectable, Component, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core';\n\n/** Apps in which we've loaded styles. */\nconst appsWithLoaders = /*#__PURE__*/new WeakMap();\n/**\n * Service that loads structural styles dynamically\n * and ensures that they're only loaded once per app.\n */\nlet _CdkPrivateStyleLoader = /*#__PURE__*/(() => {\n class _CdkPrivateStyleLoader {\n _appRef;\n _injector = inject(Injector);\n _environmentInjector = inject(EnvironmentInjector);\n /**\n * Loads a set of styles.\n * @param loader Component which will be instantiated to load the styles.\n */\n load(loader) {\n // Resolve the app ref lazily to avoid circular dependency errors if this is called too early.\n const appRef = this._appRef = this._appRef || this._injector.get(ApplicationRef);\n let data = appsWithLoaders.get(appRef);\n // If we haven't loaded for this app before, we have to initialize it.\n if (!data) {\n data = {\n loaders: new Set(),\n refs: []\n };\n appsWithLoaders.set(appRef, data);\n // When the app is destroyed, we need to clean up all the related loaders.\n appRef.onDestroy(() => {\n appsWithLoaders.get(appRef)?.refs.forEach(ref => ref.destroy());\n appsWithLoaders.delete(appRef);\n });\n }\n // If the loader hasn't been loaded before, we need to instatiate it.\n if (!data.loaders.has(loader)) {\n data.loaders.add(loader);\n data.refs.push(createComponent(loader, {\n environmentInjector: this._environmentInjector\n }));\n }\n }\n static ɵfac = function _CdkPrivateStyleLoader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || _CdkPrivateStyleLoader)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: _CdkPrivateStyleLoader,\n factory: _CdkPrivateStyleLoader.ɵfac,\n providedIn: 'root'\n });\n }\n return _CdkPrivateStyleLoader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Component used to load the .cdk-visually-hidden styles.\n * @docs-private\n */\nlet _VisuallyHiddenLoader = /*#__PURE__*/(() => {\n class _VisuallyHiddenLoader {\n static ɵfac = function _VisuallyHiddenLoader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || _VisuallyHiddenLoader)();\n };\n static ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: _VisuallyHiddenLoader,\n selectors: [[\"ng-component\"]],\n exportAs: [\"cdkVisuallyHidden\"],\n decls: 0,\n vars: 0,\n template: function _VisuallyHiddenLoader_Template(rf, ctx) {},\n styles: [\".cdk-visually-hidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;white-space:nowrap;outline:0;-webkit-appearance:none;-moz-appearance:none;left:0}[dir=rtl] .cdk-visually-hidden{left:auto;right:0}\"],\n encapsulation: 2,\n changeDetection: 0\n });\n }\n return _VisuallyHiddenLoader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { _CdkPrivateStyleLoader, _VisuallyHiddenLoader };\n","import { normalizePassiveListenerOptions, Platform } from '@angular/cdk/platform';\nimport * as i0 from '@angular/core';\nimport { Component, ChangeDetectionStrategy, ViewEncapsulation, inject, NgZone, Injectable, ElementRef, EventEmitter, Directive, Output, booleanAttribute, Input, NgModule } from '@angular/core';\nimport { _CdkPrivateStyleLoader } from '@angular/cdk/private';\nimport { coerceElement, coerceNumberProperty } from '@angular/cdk/coercion';\nimport { EMPTY, Subject, fromEvent } from 'rxjs';\nimport { DOCUMENT } from '@angular/common';\nimport { auditTime, takeUntil } from 'rxjs/operators';\n\n/** Component used to load the structural styles of the text field. */\nlet _CdkTextFieldStyleLoader = /*#__PURE__*/(() => {\n class _CdkTextFieldStyleLoader {\n static ɵfac = function _CdkTextFieldStyleLoader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || _CdkTextFieldStyleLoader)();\n };\n static ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: _CdkTextFieldStyleLoader,\n selectors: [[\"ng-component\"]],\n hostAttrs: [\"cdk-text-field-style-loader\", \"\"],\n decls: 0,\n vars: 0,\n template: function _CdkTextFieldStyleLoader_Template(rf, ctx) {},\n styles: [\"textarea.cdk-textarea-autosize{resize:none}textarea.cdk-textarea-autosize-measuring{padding:2px 0 !important;box-sizing:content-box !important;height:auto !important;overflow:hidden !important}textarea.cdk-textarea-autosize-measuring-firefox{padding:2px 0 !important;box-sizing:content-box !important;height:0 !important}@keyframes cdk-text-field-autofill-start{/*!*/}@keyframes cdk-text-field-autofill-end{/*!*/}.cdk-text-field-autofill-monitored:-webkit-autofill{animation:cdk-text-field-autofill-start 0s 1ms}.cdk-text-field-autofill-monitored:not(:-webkit-autofill){animation:cdk-text-field-autofill-end 0s 1ms}\"],\n encapsulation: 2,\n changeDetection: 0\n });\n }\n return _CdkTextFieldStyleLoader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Options to pass to the animationstart listener. */\nconst listenerOptions = /*#__PURE__*/normalizePassiveListenerOptions({\n passive: true\n});\n/**\n * An injectable service that can be used to monitor the autofill state of an input.\n * Based on the following blog post:\n * https://medium.com/@brunn/detecting-autofilled-fields-in-javascript-aed598d25da7\n */\nlet AutofillMonitor = /*#__PURE__*/(() => {\n class AutofillMonitor {\n _platform = inject(Platform);\n _ngZone = inject(NgZone);\n _styleLoader = inject(_CdkPrivateStyleLoader);\n _monitoredElements = new Map();\n constructor() {}\n monitor(elementOrRef) {\n if (!this._platform.isBrowser) {\n return EMPTY;\n }\n this._styleLoader.load(_CdkTextFieldStyleLoader);\n const element = coerceElement(elementOrRef);\n const info = this._monitoredElements.get(element);\n if (info) {\n return info.subject;\n }\n const result = new Subject();\n const cssClass = 'cdk-text-field-autofilled';\n const listener = event => {\n // Animation events fire on initial element render, we check for the presence of the autofill\n // CSS class to make sure this is a real change in state, not just the initial render before\n // we fire off events.\n if (event.animationName === 'cdk-text-field-autofill-start' && !element.classList.contains(cssClass)) {\n element.classList.add(cssClass);\n this._ngZone.run(() => result.next({\n target: event.target,\n isAutofilled: true\n }));\n } else if (event.animationName === 'cdk-text-field-autofill-end' && element.classList.contains(cssClass)) {\n element.classList.remove(cssClass);\n this._ngZone.run(() => result.next({\n target: event.target,\n isAutofilled: false\n }));\n }\n };\n this._ngZone.runOutsideAngular(() => {\n element.addEventListener('animationstart', listener, listenerOptions);\n element.classList.add('cdk-text-field-autofill-monitored');\n });\n this._monitoredElements.set(element, {\n subject: result,\n unlisten: () => {\n element.removeEventListener('animationstart', listener, listenerOptions);\n }\n });\n return result;\n }\n stopMonitoring(elementOrRef) {\n const element = coerceElement(elementOrRef);\n const info = this._monitoredElements.get(element);\n if (info) {\n info.unlisten();\n info.subject.complete();\n element.classList.remove('cdk-text-field-autofill-monitored');\n element.classList.remove('cdk-text-field-autofilled');\n this._monitoredElements.delete(element);\n }\n }\n ngOnDestroy() {\n this._monitoredElements.forEach((_info, element) => this.stopMonitoring(element));\n }\n static ɵfac = function AutofillMonitor_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || AutofillMonitor)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: AutofillMonitor,\n factory: AutofillMonitor.ɵfac,\n providedIn: 'root'\n });\n }\n return AutofillMonitor;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/** A directive that can be used to monitor the autofill state of an input. */\nlet CdkAutofill = /*#__PURE__*/(() => {\n class CdkAutofill {\n _elementRef = inject(ElementRef);\n _autofillMonitor = inject(AutofillMonitor);\n /** Emits when the autofill state of the element changes. */\n cdkAutofill = new EventEmitter();\n constructor() {}\n ngOnInit() {\n this._autofillMonitor.monitor(this._elementRef).subscribe(event => this.cdkAutofill.emit(event));\n }\n ngOnDestroy() {\n this._autofillMonitor.stopMonitoring(this._elementRef);\n }\n static ɵfac = function CdkAutofill_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || CdkAutofill)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: CdkAutofill,\n selectors: [[\"\", \"cdkAutofill\", \"\"]],\n outputs: {\n cdkAutofill: \"cdkAutofill\"\n }\n });\n }\n return CdkAutofill;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Directive to automatically resize a textarea to fit its content. */\nlet CdkTextareaAutosize = /*#__PURE__*/(() => {\n class CdkTextareaAutosize {\n _elementRef = inject(ElementRef);\n _platform = inject(Platform);\n _ngZone = inject(NgZone);\n /** Keep track of the previous textarea value to avoid resizing when the value hasn't changed. */\n _previousValue;\n _initialHeight;\n _destroyed = new Subject();\n _minRows;\n _maxRows;\n _enabled = true;\n /**\n * Value of minRows as of last resize. If the minRows has decreased, the\n * height of the textarea needs to be recomputed to reflect the new minimum. The maxHeight\n * does not have the same problem because it does not affect the textarea's scrollHeight.\n */\n _previousMinRows = -1;\n _textareaElement;\n /** Minimum amount of rows in the textarea. */\n get minRows() {\n return this._minRows;\n }\n set minRows(value) {\n this._minRows = coerceNumberProperty(value);\n this._setMinHeight();\n }\n /** Maximum amount of rows in the textarea. */\n get maxRows() {\n return this._maxRows;\n }\n set maxRows(value) {\n this._maxRows = coerceNumberProperty(value);\n this._setMaxHeight();\n }\n /** Whether autosizing is enabled or not */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n // Only act if the actual value changed. This specifically helps to not run\n // resizeToFitContent too early (i.e. before ngAfterViewInit)\n if (this._enabled !== value) {\n (this._enabled = value) ? this.resizeToFitContent(true) : this.reset();\n }\n }\n get placeholder() {\n return this._textareaElement.placeholder;\n }\n set placeholder(value) {\n this._cachedPlaceholderHeight = undefined;\n if (value) {\n this._textareaElement.setAttribute('placeholder', value);\n } else {\n this._textareaElement.removeAttribute('placeholder');\n }\n this._cacheTextareaPlaceholderHeight();\n }\n /** Cached height of a textarea with a single row. */\n _cachedLineHeight;\n /** Cached height of a textarea with only the placeholder. */\n _cachedPlaceholderHeight;\n /** Used to reference correct document/window */\n _document = inject(DOCUMENT, {\n optional: true\n });\n _hasFocus;\n _isViewInited = false;\n constructor() {\n const styleLoader = inject(_CdkPrivateStyleLoader);\n styleLoader.load(_CdkTextFieldStyleLoader);\n this._textareaElement = this._elementRef.nativeElement;\n }\n /** Sets the minimum height of the textarea as determined by minRows. */\n _setMinHeight() {\n const minHeight = this.minRows && this._cachedLineHeight ? `${this.minRows * this._cachedLineHeight}px` : null;\n if (minHeight) {\n this._textareaElement.style.minHeight = minHeight;\n }\n }\n /** Sets the maximum height of the textarea as determined by maxRows. */\n _setMaxHeight() {\n const maxHeight = this.maxRows && this._cachedLineHeight ? `${this.maxRows * this._cachedLineHeight}px` : null;\n if (maxHeight) {\n this._textareaElement.style.maxHeight = maxHeight;\n }\n }\n ngAfterViewInit() {\n if (this._platform.isBrowser) {\n // Remember the height which we started with in case autosizing is disabled\n this._initialHeight = this._textareaElement.style.height;\n this.resizeToFitContent();\n this._ngZone.runOutsideAngular(() => {\n const window = this._getWindow();\n fromEvent(window, 'resize').pipe(auditTime(16), takeUntil(this._destroyed)).subscribe(() => this.resizeToFitContent(true));\n this._textareaElement.addEventListener('focus', this._handleFocusEvent);\n this._textareaElement.addEventListener('blur', this._handleFocusEvent);\n });\n this._isViewInited = true;\n this.resizeToFitContent(true);\n }\n }\n ngOnDestroy() {\n this._textareaElement.removeEventListener('focus', this._handleFocusEvent);\n this._textareaElement.removeEventListener('blur', this._handleFocusEvent);\n this._destroyed.next();\n this._destroyed.complete();\n }\n /**\n * Cache the height of a single-row textarea if it has not already been cached.\n *\n * We need to know how large a single \"row\" of a textarea is in order to apply minRows and\n * maxRows. For the initial version, we will assume that the height of a single line in the\n * textarea does not ever change.\n */\n _cacheTextareaLineHeight() {\n if (this._cachedLineHeight) {\n return;\n }\n // Use a clone element because we have to override some styles.\n let textareaClone = this._textareaElement.cloneNode(false);\n textareaClone.rows = 1;\n // Use `position: absolute` so that this doesn't cause a browser layout and use\n // `visibility: hidden` so that nothing is rendered. Clear any other styles that\n // would affect the height.\n textareaClone.style.position = 'absolute';\n textareaClone.style.visibility = 'hidden';\n textareaClone.style.border = 'none';\n textareaClone.style.padding = '0';\n textareaClone.style.height = '';\n textareaClone.style.minHeight = '';\n textareaClone.style.maxHeight = '';\n // In Firefox it happens that textarea elements are always bigger than the specified amount\n // of rows. This is because Firefox tries to add extra space for the horizontal scrollbar.\n // As a workaround that removes the extra space for the scrollbar, we can just set overflow\n // to hidden. This ensures that there is no invalid calculation of the line height.\n // See Firefox bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=33654\n textareaClone.style.overflow = 'hidden';\n this._textareaElement.parentNode.appendChild(textareaClone);\n this._cachedLineHeight = textareaClone.clientHeight;\n textareaClone.remove();\n // Min and max heights have to be re-calculated if the cached line height changes\n this._setMinHeight();\n this._setMaxHeight();\n }\n _measureScrollHeight() {\n const element = this._textareaElement;\n const previousMargin = element.style.marginBottom || '';\n const isFirefox = this._platform.FIREFOX;\n const needsMarginFiller = isFirefox && this._hasFocus;\n const measuringClass = isFirefox ? 'cdk-textarea-autosize-measuring-firefox' : 'cdk-textarea-autosize-measuring';\n // In some cases the page might move around while we're measuring the `textarea` on Firefox. We\n // work around it by assigning a temporary margin with the same height as the `textarea` so that\n // it occupies the same amount of space. See #23233.\n if (needsMarginFiller) {\n element.style.marginBottom = `${element.clientHeight}px`;\n }\n // Reset the textarea height to auto in order to shrink back to its default size.\n // Also temporarily force overflow:hidden, so scroll bars do not interfere with calculations.\n element.classList.add(measuringClass);\n // The measuring class includes a 2px padding to workaround an issue with Chrome,\n // so we account for that extra space here by subtracting 4 (2px top + 2px bottom).\n const scrollHeight = element.scrollHeight - 4;\n element.classList.remove(measuringClass);\n if (needsMarginFiller) {\n element.style.marginBottom = previousMargin;\n }\n return scrollHeight;\n }\n _cacheTextareaPlaceholderHeight() {\n if (!this._isViewInited || this._cachedPlaceholderHeight != undefined) {\n return;\n }\n if (!this.placeholder) {\n this._cachedPlaceholderHeight = 0;\n return;\n }\n const value = this._textareaElement.value;\n this._textareaElement.value = this._textareaElement.placeholder;\n this._cachedPlaceholderHeight = this._measureScrollHeight();\n this._textareaElement.value = value;\n }\n /** Handles `focus` and `blur` events. */\n _handleFocusEvent = event => {\n this._hasFocus = event.type === 'focus';\n };\n ngDoCheck() {\n if (this._platform.isBrowser) {\n this.resizeToFitContent();\n }\n }\n /**\n * Resize the textarea to fit its content.\n * @param force Whether to force a height recalculation. By default the height will be\n * recalculated only if the value changed since the last call.\n */\n resizeToFitContent(force = false) {\n // If autosizing is disabled, just skip everything else\n if (!this._enabled) {\n return;\n }\n this._cacheTextareaLineHeight();\n this._cacheTextareaPlaceholderHeight();\n // If we haven't determined the line-height yet, we know we're still hidden and there's no point\n // in checking the height of the textarea.\n if (!this._cachedLineHeight) {\n return;\n }\n const textarea = this._elementRef.nativeElement;\n const value = textarea.value;\n // Only resize if the value or minRows have changed since these calculations can be expensive.\n if (!force && this._minRows === this._previousMinRows && value === this._previousValue) {\n return;\n }\n const scrollHeight = this._measureScrollHeight();\n const height = Math.max(scrollHeight, this._cachedPlaceholderHeight || 0);\n // Use the scrollHeight to know how large the textarea *would* be if fit its entire value.\n textarea.style.height = `${height}px`;\n this._ngZone.runOutsideAngular(() => {\n if (typeof requestAnimationFrame !== 'undefined') {\n requestAnimationFrame(() => this._scrollToCaretPosition(textarea));\n } else {\n setTimeout(() => this._scrollToCaretPosition(textarea));\n }\n });\n this._previousValue = value;\n this._previousMinRows = this._minRows;\n }\n /**\n * Resets the textarea to its original size\n */\n reset() {\n // Do not try to change the textarea, if the initialHeight has not been determined yet\n // This might potentially remove styles when reset() is called before ngAfterViewInit\n if (this._initialHeight !== undefined) {\n this._textareaElement.style.height = this._initialHeight;\n }\n }\n _noopInputHandler() {\n // no-op handler that ensures we're running change detection on input events.\n }\n /** Access injected document if available or fallback to global document reference */\n _getDocument() {\n return this._document || document;\n }\n /** Use defaultView of injected document if available or fallback to global window reference */\n _getWindow() {\n const doc = this._getDocument();\n return doc.defaultView || window;\n }\n /**\n * Scrolls a textarea to the caret position. On Firefox resizing the textarea will\n * prevent it from scrolling to the caret position. We need to re-set the selection\n * in order for it to scroll to the proper position.\n */\n _scrollToCaretPosition(textarea) {\n const {\n selectionStart,\n selectionEnd\n } = textarea;\n // IE will throw an \"Unspecified error\" if we try to set the selection range after the\n // element has been removed from the DOM. Assert that the directive hasn't been destroyed\n // between the time we requested the animation frame and when it was executed.\n // Also note that we have to assert that the textarea is focused before we set the\n // selection range. Setting the selection range on a non-focused textarea will cause\n // it to receive focus on IE and Edge.\n if (!this._destroyed.isStopped && this._hasFocus) {\n textarea.setSelectionRange(selectionStart, selectionEnd);\n }\n }\n static ɵfac = function CdkTextareaAutosize_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || CdkTextareaAutosize)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: CdkTextareaAutosize,\n selectors: [[\"textarea\", \"cdkTextareaAutosize\", \"\"]],\n hostAttrs: [\"rows\", \"1\", 1, \"cdk-textarea-autosize\"],\n hostBindings: function CdkTextareaAutosize_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"input\", function CdkTextareaAutosize_input_HostBindingHandler() {\n return ctx._noopInputHandler();\n });\n }\n },\n inputs: {\n minRows: [0, \"cdkAutosizeMinRows\", \"minRows\"],\n maxRows: [0, \"cdkAutosizeMaxRows\", \"maxRows\"],\n enabled: [2, \"cdkTextareaAutosize\", \"enabled\", booleanAttribute],\n placeholder: \"placeholder\"\n },\n exportAs: [\"cdkTextareaAutosize\"],\n features: [i0.ɵɵInputTransformsFeature]\n });\n }\n return CdkTextareaAutosize;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet TextFieldModule = /*#__PURE__*/(() => {\n class TextFieldModule {\n static ɵfac = function TextFieldModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || TextFieldModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: TextFieldModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({});\n }\n return TextFieldModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { AutofillMonitor, CdkAutofill, CdkTextareaAutosize, TextFieldModule };\n","import { DOCUMENT } from '@angular/common';\nimport * as i0 from '@angular/core';\nimport { inject, APP_ID, Injectable, signal, QueryList, isSignal, effect, InjectionToken, afterNextRender, NgZone, Injector, ElementRef, booleanAttribute, Directive, Input, EventEmitter, Output, NgModule } from '@angular/core';\nimport { Platform, _getFocusedElementPierceShadowDom, normalizePassiveListenerOptions, _getEventTarget, _getShadowRoot } from '@angular/cdk/platform';\nimport { _CdkPrivateStyleLoader, _VisuallyHiddenLoader } from '@angular/cdk/private';\nimport { A, Z, ZERO, NINE, hasModifierKey, PAGE_DOWN, PAGE_UP, END, HOME, LEFT_ARROW, RIGHT_ARROW, UP_ARROW, DOWN_ARROW, TAB, ALT, CONTROL, MAC_META, META, SHIFT } from '@angular/cdk/keycodes';\nimport { Subject, Subscription, isObservable, of, BehaviorSubject } from 'rxjs';\nimport { tap, debounceTime, filter, map, take, skip, distinctUntilChanged, takeUntil } from 'rxjs/operators';\nimport { coerceObservable } from '@angular/cdk/coercion/private';\nimport { ContentObserver, ObserversModule } from '@angular/cdk/observers';\nimport { coerceElement } from '@angular/cdk/coercion';\nimport { BreakpointObserver } from '@angular/cdk/layout';\n\n/** IDs are delimited by an empty space, as per the spec. */\nconst ID_DELIMITER = ' ';\n/**\n * Adds the given ID to the specified ARIA attribute on an element.\n * Used for attributes such as aria-labelledby, aria-owns, etc.\n */\nfunction addAriaReferencedId(el, attr, id) {\n const ids = getAriaReferenceIds(el, attr);\n id = id.trim();\n if (ids.some(existingId => existingId.trim() === id)) {\n return;\n }\n ids.push(id);\n el.setAttribute(attr, ids.join(ID_DELIMITER));\n}\n/**\n * Removes the given ID from the specified ARIA attribute on an element.\n * Used for attributes such as aria-labelledby, aria-owns, etc.\n */\nfunction removeAriaReferencedId(el, attr, id) {\n const ids = getAriaReferenceIds(el, attr);\n id = id.trim();\n const filteredIds = ids.filter(val => val !== id);\n if (filteredIds.length) {\n el.setAttribute(attr, filteredIds.join(ID_DELIMITER));\n } else {\n el.removeAttribute(attr);\n }\n}\n/**\n * Gets the list of IDs referenced by the given ARIA attribute on an element.\n * Used for attributes such as aria-labelledby, aria-owns, etc.\n */\nfunction getAriaReferenceIds(el, attr) {\n // Get string array of all individual ids (whitespace delimited) in the attribute value\n const attrValue = el.getAttribute(attr);\n return attrValue?.match(/\\S+/g) ?? [];\n}\n\n/**\n * ID used for the body container where all messages are appended.\n * @deprecated No longer being used. To be removed.\n * @breaking-change 14.0.0\n */\nconst MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';\n/**\n * ID prefix used for each created message element.\n * @deprecated To be turned into a private variable.\n * @breaking-change 14.0.0\n */\nconst CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';\n/**\n * Attribute given to each host element that is described by a message element.\n * @deprecated To be turned into a private variable.\n * @breaking-change 14.0.0\n */\nconst CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';\n/** Global incremental identifier for each registered message element. */\nlet nextId = 0;\n/**\n * Utility that creates visually hidden elements with a message content. Useful for elements that\n * want to use aria-describedby to further describe themselves without adding additional visual\n * content.\n */\nlet AriaDescriber = /*#__PURE__*/(() => {\n class AriaDescriber {\n _platform = inject(Platform);\n _document = inject(DOCUMENT);\n /** Map of all registered message elements that have been placed into the document. */\n _messageRegistry = new Map();\n /** Container for all registered messages. */\n _messagesContainer = null;\n /** Unique ID for the service. */\n _id = `${nextId++}`;\n constructor() {\n inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);\n this._id = inject(APP_ID) + '-' + nextId++;\n }\n describe(hostElement, message, role) {\n if (!this._canBeDescribed(hostElement, message)) {\n return;\n }\n const key = getKey(message, role);\n if (typeof message !== 'string') {\n // We need to ensure that the element has an ID.\n setMessageId(message, this._id);\n this._messageRegistry.set(key, {\n messageElement: message,\n referenceCount: 0\n });\n } else if (!this._messageRegistry.has(key)) {\n this._createMessageElement(message, role);\n }\n if (!this._isElementDescribedByMessage(hostElement, key)) {\n this._addMessageReference(hostElement, key);\n }\n }\n removeDescription(hostElement, message, role) {\n if (!message || !this._isElementNode(hostElement)) {\n return;\n }\n const key = getKey(message, role);\n if (this._isElementDescribedByMessage(hostElement, key)) {\n this._removeMessageReference(hostElement, key);\n }\n // If the message is a string, it means that it's one that we created for the\n // consumer so we can remove it safely, otherwise we should leave it in place.\n if (typeof message === 'string') {\n const registeredMessage = this._messageRegistry.get(key);\n if (registeredMessage && registeredMessage.referenceCount === 0) {\n this._deleteMessageElement(key);\n }\n }\n if (this._messagesContainer?.childNodes.length === 0) {\n this._messagesContainer.remove();\n this._messagesContainer = null;\n }\n }\n /** Unregisters all created message elements and removes the message container. */\n ngOnDestroy() {\n const describedElements = this._document.querySelectorAll(`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}=\"${this._id}\"]`);\n for (let i = 0; i < describedElements.length; i++) {\n this._removeCdkDescribedByReferenceIds(describedElements[i]);\n describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);\n }\n this._messagesContainer?.remove();\n this._messagesContainer = null;\n this._messageRegistry.clear();\n }\n /**\n * Creates a new element in the visually hidden message container element with the message\n * as its content and adds it to the message registry.\n */\n _createMessageElement(message, role) {\n const messageElement = this._document.createElement('div');\n setMessageId(messageElement, this._id);\n messageElement.textContent = message;\n if (role) {\n messageElement.setAttribute('role', role);\n }\n this._createMessagesContainer();\n this._messagesContainer.appendChild(messageElement);\n this._messageRegistry.set(getKey(message, role), {\n messageElement,\n referenceCount: 0\n });\n }\n /** Deletes the message element from the global messages container. */\n _deleteMessageElement(key) {\n this._messageRegistry.get(key)?.messageElement?.remove();\n this._messageRegistry.delete(key);\n }\n /** Creates the global container for all aria-describedby messages. */\n _createMessagesContainer() {\n if (this._messagesContainer) {\n return;\n }\n const containerClassName = 'cdk-describedby-message-container';\n const serverContainers = this._document.querySelectorAll(`.${containerClassName}[platform=\"server\"]`);\n for (let i = 0; i < serverContainers.length; i++) {\n // When going from the server to the client, we may end up in a situation where there's\n // already a container on the page, but we don't have a reference to it. Clear the\n // old container so we don't get duplicates. Doing this, instead of emptying the previous\n // container, should be slightly faster.\n serverContainers[i].remove();\n }\n const messagesContainer = this._document.createElement('div');\n // We add `visibility: hidden` in order to prevent text in this container from\n // being searchable by the browser's Ctrl + F functionality.\n // Screen-readers will still read the description for elements with aria-describedby even\n // when the description element is not visible.\n messagesContainer.style.visibility = 'hidden';\n // Even though we use `visibility: hidden`, we still apply `cdk-visually-hidden` so that\n // the description element doesn't impact page layout.\n messagesContainer.classList.add(containerClassName);\n messagesContainer.classList.add('cdk-visually-hidden');\n if (!this._platform.isBrowser) {\n messagesContainer.setAttribute('platform', 'server');\n }\n this._document.body.appendChild(messagesContainer);\n this._messagesContainer = messagesContainer;\n }\n /** Removes all cdk-describedby messages that are hosted through the element. */\n _removeCdkDescribedByReferenceIds(element) {\n // Remove all aria-describedby reference IDs that are prefixed by CDK_DESCRIBEDBY_ID_PREFIX\n const originalReferenceIds = getAriaReferenceIds(element, 'aria-describedby').filter(id => id.indexOf(CDK_DESCRIBEDBY_ID_PREFIX) != 0);\n element.setAttribute('aria-describedby', originalReferenceIds.join(' '));\n }\n /**\n * Adds a message reference to the element using aria-describedby and increments the registered\n * message's reference count.\n */\n _addMessageReference(element, key) {\n const registeredMessage = this._messageRegistry.get(key);\n // Add the aria-describedby reference and set the\n // describedby_host attribute to mark the element.\n addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);\n element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, this._id);\n registeredMessage.referenceCount++;\n }\n /**\n * Removes a message reference from the element using aria-describedby\n * and decrements the registered message's reference count.\n */\n _removeMessageReference(element, key) {\n const registeredMessage = this._messageRegistry.get(key);\n registeredMessage.referenceCount--;\n removeAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);\n element.removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);\n }\n /** Returns true if the element has been described by the provided message ID. */\n _isElementDescribedByMessage(element, key) {\n const referenceIds = getAriaReferenceIds(element, 'aria-describedby');\n const registeredMessage = this._messageRegistry.get(key);\n const messageId = registeredMessage && registeredMessage.messageElement.id;\n return !!messageId && referenceIds.indexOf(messageId) != -1;\n }\n /** Determines whether a message can be described on a particular element. */\n _canBeDescribed(element, message) {\n if (!this._isElementNode(element)) {\n return false;\n }\n if (message && typeof message === 'object') {\n // We'd have to make some assumptions about the description element's text, if the consumer\n // passed in an element. Assume that if an element is passed in, the consumer has verified\n // that it can be used as a description.\n return true;\n }\n const trimmedMessage = message == null ? '' : `${message}`.trim();\n const ariaLabel = element.getAttribute('aria-label');\n // We shouldn't set descriptions if they're exactly the same as the `aria-label` of the\n // element, because screen readers will end up reading out the same text twice in a row.\n return trimmedMessage ? !ariaLabel || ariaLabel.trim() !== trimmedMessage : false;\n }\n /** Checks whether a node is an Element node. */\n _isElementNode(element) {\n return element.nodeType === this._document.ELEMENT_NODE;\n }\n static ɵfac = function AriaDescriber_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || AriaDescriber)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: AriaDescriber,\n factory: AriaDescriber.ɵfac,\n providedIn: 'root'\n });\n }\n return AriaDescriber;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/** Gets a key that can be used to look messages up in the registry. */\nfunction getKey(message, role) {\n return typeof message === 'string' ? `${role || ''}/${message}` : message;\n}\n/** Assigns a unique ID to an element, if it doesn't have one already. */\nfunction setMessageId(element, serviceId) {\n if (!element.id) {\n element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${serviceId}-${nextId++}`;\n }\n}\nconst DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL_MS = 200;\n/**\n * Selects items based on keyboard inputs. Implements the typeahead functionality of\n * `role=\"listbox\"` or `role=\"tree\"` and other related roles.\n */\nclass Typeahead {\n _letterKeyStream = /*#__PURE__*/new Subject();\n _items = [];\n _selectedItemIndex = -1;\n /** Buffer for the letters that the user has pressed */\n _pressedLetters = [];\n _skipPredicateFn;\n _selectedItem = /*#__PURE__*/new Subject();\n selectedItem = this._selectedItem;\n constructor(initialItems, config) {\n const typeAheadInterval = typeof config?.debounceInterval === 'number' ? config.debounceInterval : DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL_MS;\n if (config?.skipPredicate) {\n this._skipPredicateFn = config.skipPredicate;\n }\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && initialItems.length && initialItems.some(item => typeof item.getLabel !== 'function')) {\n throw new Error('KeyManager items in typeahead mode must implement the `getLabel` method.');\n }\n this.setItems(initialItems);\n this._setupKeyHandler(typeAheadInterval);\n }\n destroy() {\n this._pressedLetters = [];\n this._letterKeyStream.complete();\n this._selectedItem.complete();\n }\n setCurrentSelectedItemIndex(index) {\n this._selectedItemIndex = index;\n }\n setItems(items) {\n this._items = items;\n }\n handleKey(event) {\n const keyCode = event.keyCode;\n // Attempt to use the `event.key` which also maps it to the user's keyboard language,\n // otherwise fall back to resolving alphanumeric characters via the keyCode.\n if (event.key && event.key.length === 1) {\n this._letterKeyStream.next(event.key.toLocaleUpperCase());\n } else if (keyCode >= A && keyCode <= Z || keyCode >= ZERO && keyCode <= NINE) {\n this._letterKeyStream.next(String.fromCharCode(keyCode));\n }\n }\n /** Gets whether the user is currently typing into the manager using the typeahead feature. */\n isTyping() {\n return this._pressedLetters.length > 0;\n }\n /** Resets the currently stored sequence of typed letters. */\n reset() {\n this._pressedLetters = [];\n }\n _setupKeyHandler(typeAheadInterval) {\n // Debounce the presses of non-navigational keys, collect the ones that correspond to letters\n // and convert those letters back into a string. Afterwards find the first item that starts\n // with that string and select it.\n this._letterKeyStream.pipe(tap(letter => this._pressedLetters.push(letter)), debounceTime(typeAheadInterval), filter(() => this._pressedLetters.length > 0), map(() => this._pressedLetters.join('').toLocaleUpperCase())).subscribe(inputString => {\n // Start at 1 because we want to start searching at the item immediately\n // following the current active item.\n for (let i = 1; i < this._items.length + 1; i++) {\n const index = (this._selectedItemIndex + i) % this._items.length;\n const item = this._items[index];\n if (!this._skipPredicateFn?.(item) && item.getLabel?.().toLocaleUpperCase().trim().indexOf(inputString) === 0) {\n this._selectedItem.next(item);\n break;\n }\n }\n this._pressedLetters = [];\n });\n }\n}\n\n/**\n * This class manages keyboard events for selectable lists. If you pass it a query list\n * of items, it will set the active item correctly when arrow events occur.\n */\nclass ListKeyManager {\n _items;\n _activeItemIndex = -1;\n _activeItem = /*#__PURE__*/signal(null);\n _wrap = false;\n _typeaheadSubscription = Subscription.EMPTY;\n _itemChangesSubscription;\n _vertical = true;\n _horizontal;\n _allowedModifierKeys = [];\n _homeAndEnd = false;\n _pageUpAndDown = {\n enabled: false,\n delta: 10\n };\n _effectRef;\n _typeahead;\n /**\n * Predicate function that can be used to check whether an item should be skipped\n * by the key manager. By default, disabled items are skipped.\n */\n _skipPredicateFn = item => item.disabled;\n constructor(_items, injector) {\n this._items = _items;\n // We allow for the items to be an array because, in some cases, the consumer may\n // not have access to a QueryList of the items they want to manage (e.g. when the\n // items aren't being collected via `ViewChildren` or `ContentChildren`).\n if (_items instanceof QueryList) {\n this._itemChangesSubscription = _items.changes.subscribe(newItems => this._itemsChanged(newItems.toArray()));\n } else if (isSignal(_items)) {\n if (!injector && (typeof ngDevMode === 'undefined' || ngDevMode)) {\n throw new Error('ListKeyManager constructed with a signal must receive an injector');\n }\n this._effectRef = effect(() => this._itemsChanged(_items()), {\n injector\n });\n }\n }\n /**\n * Stream that emits any time the TAB key is pressed, so components can react\n * when focus is shifted off of the list.\n */\n tabOut = /*#__PURE__*/new Subject();\n /** Stream that emits whenever the active item of the list manager changes. */\n change = /*#__PURE__*/new Subject();\n /**\n * Sets the predicate function that determines which items should be skipped by the\n * list key manager.\n * @param predicate Function that determines whether the given item should be skipped.\n */\n skipPredicate(predicate) {\n this._skipPredicateFn = predicate;\n return this;\n }\n /**\n * Configures wrapping mode, which determines whether the active item will wrap to\n * the other end of list when there are no more items in the given direction.\n * @param shouldWrap Whether the list should wrap when reaching the end.\n */\n withWrap(shouldWrap = true) {\n this._wrap = shouldWrap;\n return this;\n }\n /**\n * Configures whether the key manager should be able to move the selection vertically.\n * @param enabled Whether vertical selection should be enabled.\n */\n withVerticalOrientation(enabled = true) {\n this._vertical = enabled;\n return this;\n }\n /**\n * Configures the key manager to move the selection horizontally.\n * Passing in `null` will disable horizontal movement.\n * @param direction Direction in which the selection can be moved.\n */\n withHorizontalOrientation(direction) {\n this._horizontal = direction;\n return this;\n }\n /**\n * Modifier keys which are allowed to be held down and whose default actions will be prevented\n * as the user is pressing the arrow keys. Defaults to not allowing any modifier keys.\n */\n withAllowedModifierKeys(keys) {\n this._allowedModifierKeys = keys;\n return this;\n }\n /**\n * Turns on typeahead mode which allows users to set the active item by typing.\n * @param debounceInterval Time to wait after the last keystroke before setting the active item.\n */\n withTypeAhead(debounceInterval = 200) {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n const items = this._getItemsArray();\n if (items.length > 0 && items.some(item => typeof item.getLabel !== 'function')) {\n throw Error('ListKeyManager items in typeahead mode must implement the `getLabel` method.');\n }\n }\n this._typeaheadSubscription.unsubscribe();\n const items = this._getItemsArray();\n this._typeahead = new Typeahead(items, {\n debounceInterval: typeof debounceInterval === 'number' ? debounceInterval : undefined,\n skipPredicate: item => this._skipPredicateFn(item)\n });\n this._typeaheadSubscription = this._typeahead.selectedItem.subscribe(item => {\n this.setActiveItem(item);\n });\n return this;\n }\n /** Cancels the current typeahead sequence. */\n cancelTypeahead() {\n this._typeahead?.reset();\n return this;\n }\n /**\n * Configures the key manager to activate the first and last items\n * respectively when the Home or End key is pressed.\n * @param enabled Whether pressing the Home or End key activates the first/last item.\n */\n withHomeAndEnd(enabled = true) {\n this._homeAndEnd = enabled;\n return this;\n }\n /**\n * Configures the key manager to activate every 10th, configured or first/last element in up/down direction\n * respectively when the Page-Up or Page-Down key is pressed.\n * @param enabled Whether pressing the Page-Up or Page-Down key activates the first/last item.\n * @param delta Whether pressing the Home or End key activates the first/last item.\n */\n withPageUpDown(enabled = true, delta = 10) {\n this._pageUpAndDown = {\n enabled,\n delta\n };\n return this;\n }\n setActiveItem(item) {\n const previousActiveItem = this._activeItem();\n this.updateActiveItem(item);\n if (this._activeItem() !== previousActiveItem) {\n this.change.next(this._activeItemIndex);\n }\n }\n /**\n * Sets the active item depending on the key event passed in.\n * @param event Keyboard event to be used for determining which element should be active.\n */\n onKeydown(event) {\n const keyCode = event.keyCode;\n const modifiers = ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'];\n const isModifierAllowed = modifiers.every(modifier => {\n return !event[modifier] || this._allowedModifierKeys.indexOf(modifier) > -1;\n });\n switch (keyCode) {\n case TAB:\n this.tabOut.next();\n return;\n case DOWN_ARROW:\n if (this._vertical && isModifierAllowed) {\n this.setNextItemActive();\n break;\n } else {\n return;\n }\n case UP_ARROW:\n if (this._vertical && isModifierAllowed) {\n this.setPreviousItemActive();\n break;\n } else {\n return;\n }\n case RIGHT_ARROW:\n if (this._horizontal && isModifierAllowed) {\n this._horizontal === 'rtl' ? this.setPreviousItemActive() : this.setNextItemActive();\n break;\n } else {\n return;\n }\n case LEFT_ARROW:\n if (this._horizontal && isModifierAllowed) {\n this._horizontal === 'rtl' ? this.setNextItemActive() : this.setPreviousItemActive();\n break;\n } else {\n return;\n }\n case HOME:\n if (this._homeAndEnd && isModifierAllowed) {\n this.setFirstItemActive();\n break;\n } else {\n return;\n }\n case END:\n if (this._homeAndEnd && isModifierAllowed) {\n this.setLastItemActive();\n break;\n } else {\n return;\n }\n case PAGE_UP:\n if (this._pageUpAndDown.enabled && isModifierAllowed) {\n const targetIndex = this._activeItemIndex - this._pageUpAndDown.delta;\n this._setActiveItemByIndex(targetIndex > 0 ? targetIndex : 0, 1);\n break;\n } else {\n return;\n }\n case PAGE_DOWN:\n if (this._pageUpAndDown.enabled && isModifierAllowed) {\n const targetIndex = this._activeItemIndex + this._pageUpAndDown.delta;\n const itemsLength = this._getItemsArray().length;\n this._setActiveItemByIndex(targetIndex < itemsLength ? targetIndex : itemsLength - 1, -1);\n break;\n } else {\n return;\n }\n default:\n if (isModifierAllowed || hasModifierKey(event, 'shiftKey')) {\n this._typeahead?.handleKey(event);\n }\n // Note that we return here, in order to avoid preventing\n // the default action of non-navigational keys.\n return;\n }\n this._typeahead?.reset();\n event.preventDefault();\n }\n /** Index of the currently active item. */\n get activeItemIndex() {\n return this._activeItemIndex;\n }\n /** The active item. */\n get activeItem() {\n return this._activeItem();\n }\n /** Gets whether the user is currently typing into the manager using the typeahead feature. */\n isTyping() {\n return !!this._typeahead && this._typeahead.isTyping();\n }\n /** Sets the active item to the first enabled item in the list. */\n setFirstItemActive() {\n this._setActiveItemByIndex(0, 1);\n }\n /** Sets the active item to the last enabled item in the list. */\n setLastItemActive() {\n this._setActiveItemByIndex(this._getItemsArray().length - 1, -1);\n }\n /** Sets the active item to the next enabled item in the list. */\n setNextItemActive() {\n this._activeItemIndex < 0 ? this.setFirstItemActive() : this._setActiveItemByDelta(1);\n }\n /** Sets the active item to a previous enabled item in the list. */\n setPreviousItemActive() {\n this._activeItemIndex < 0 && this._wrap ? this.setLastItemActive() : this._setActiveItemByDelta(-1);\n }\n updateActiveItem(item) {\n const itemArray = this._getItemsArray();\n const index = typeof item === 'number' ? item : itemArray.indexOf(item);\n const activeItem = itemArray[index];\n // Explicitly check for `null` and `undefined` because other falsy values are valid.\n this._activeItem.set(activeItem == null ? null : activeItem);\n this._activeItemIndex = index;\n this._typeahead?.setCurrentSelectedItemIndex(index);\n }\n /** Cleans up the key manager. */\n destroy() {\n this._typeaheadSubscription.unsubscribe();\n this._itemChangesSubscription?.unsubscribe();\n this._effectRef?.destroy();\n this._typeahead?.destroy();\n this.tabOut.complete();\n this.change.complete();\n }\n /**\n * This method sets the active item, given a list of items and the delta between the\n * currently active item and the new active item. It will calculate differently\n * depending on whether wrap mode is turned on.\n */\n _setActiveItemByDelta(delta) {\n this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);\n }\n /**\n * Sets the active item properly given \"wrap\" mode. In other words, it will continue to move\n * down the list until it finds an item that is not disabled, and it will wrap if it\n * encounters either end of the list.\n */\n _setActiveInWrapMode(delta) {\n const items = this._getItemsArray();\n for (let i = 1; i <= items.length; i++) {\n const index = (this._activeItemIndex + delta * i + items.length) % items.length;\n const item = items[index];\n if (!this._skipPredicateFn(item)) {\n this.setActiveItem(index);\n return;\n }\n }\n }\n /**\n * Sets the active item properly given the default mode. In other words, it will\n * continue to move down the list until it finds an item that is not disabled. If\n * it encounters either end of the list, it will stop and not wrap.\n */\n _setActiveInDefaultMode(delta) {\n this._setActiveItemByIndex(this._activeItemIndex + delta, delta);\n }\n /**\n * Sets the active item to the first enabled item starting at the index specified. If the\n * item is disabled, it will move in the fallbackDelta direction until it either\n * finds an enabled item or encounters the end of the list.\n */\n _setActiveItemByIndex(index, fallbackDelta) {\n const items = this._getItemsArray();\n if (!items[index]) {\n return;\n }\n while (this._skipPredicateFn(items[index])) {\n index += fallbackDelta;\n if (!items[index]) {\n return;\n }\n }\n this.setActiveItem(index);\n }\n /** Returns the items as an array. */\n _getItemsArray() {\n if (isSignal(this._items)) {\n return this._items();\n }\n return this._items instanceof QueryList ? this._items.toArray() : this._items;\n }\n /** Callback for when the items have changed. */\n _itemsChanged(newItems) {\n this._typeahead?.setItems(newItems);\n const activeItem = this._activeItem();\n if (activeItem) {\n const newIndex = newItems.indexOf(activeItem);\n if (newIndex > -1 && newIndex !== this._activeItemIndex) {\n this._activeItemIndex = newIndex;\n this._typeahead?.setCurrentSelectedItemIndex(newIndex);\n }\n }\n }\n}\nclass ActiveDescendantKeyManager extends ListKeyManager {\n setActiveItem(index) {\n if (this.activeItem) {\n this.activeItem.setInactiveStyles();\n }\n super.setActiveItem(index);\n if (this.activeItem) {\n this.activeItem.setActiveStyles();\n }\n }\n}\nclass FocusKeyManager extends ListKeyManager {\n _origin = 'program';\n /**\n * Sets the focus origin that will be passed in to the items for any subsequent `focus` calls.\n * @param origin Focus origin to be used when focusing items.\n */\n setFocusOrigin(origin) {\n this._origin = origin;\n return this;\n }\n setActiveItem(item) {\n super.setActiveItem(item);\n if (this.activeItem) {\n this.activeItem.focus(this._origin);\n }\n }\n}\n\n/**\n * This class manages keyboard events for trees. If you pass it a QueryList or other list of tree\n * items, it will set the active item, focus, handle expansion and typeahead correctly when\n * keyboard events occur.\n */\nclass TreeKeyManager {\n /** The index of the currently active (focused) item. */\n _activeItemIndex = -1;\n /** The currently active (focused) item. */\n _activeItem = null;\n /** Whether or not we activate the item when it's focused. */\n _shouldActivationFollowFocus = false;\n /**\n * The orientation that the tree is laid out in. In `rtl` mode, the behavior of Left and\n * Right arrow are switched.\n */\n _horizontalOrientation = 'ltr';\n /**\n * Predicate function that can be used to check whether an item should be skipped\n * by the key manager.\n *\n * The default value for this doesn't skip any elements in order to keep tree items focusable\n * when disabled. This aligns with ARIA guidelines:\n * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#focusabilityofdisabledcontrols.\n */\n _skipPredicateFn = _item => false;\n /** Function to determine equivalent items. */\n _trackByFn = item => item;\n /** Synchronous cache of the items to manage. */\n _items = [];\n _typeahead;\n _typeaheadSubscription = Subscription.EMPTY;\n _hasInitialFocused = false;\n _initializeFocus() {\n if (this._hasInitialFocused || this._items.length === 0) {\n return;\n }\n let activeIndex = 0;\n for (let i = 0; i < this._items.length; i++) {\n if (!this._skipPredicateFn(this._items[i]) && !this._isItemDisabled(this._items[i])) {\n activeIndex = i;\n break;\n }\n }\n const activeItem = this._items[activeIndex];\n // Use `makeFocusable` here, because we want the item to just be focusable, not actually\n // capture the focus since the user isn't interacting with it. See #29628.\n if (activeItem.makeFocusable) {\n this._activeItem?.unfocus();\n this._activeItemIndex = activeIndex;\n this._activeItem = activeItem;\n this._typeahead?.setCurrentSelectedItemIndex(activeIndex);\n activeItem.makeFocusable();\n } else {\n // Backwards compatibility for items that don't implement `makeFocusable`.\n this.focusItem(activeIndex);\n }\n this._hasInitialFocused = true;\n }\n /**\n *\n * @param items List of TreeKeyManager options. Can be synchronous or asynchronous.\n * @param config Optional configuration options. By default, use 'ltr' horizontal orientation. By\n * default, do not skip any nodes. By default, key manager only calls `focus` method when items\n * are focused and does not call `activate`. If `typeaheadDefaultInterval` is `true`, use a\n * default interval of 200ms.\n */\n constructor(items, config) {\n // We allow for the items to be an array or Observable because, in some cases, the consumer may\n // not have access to a QueryList of the items they want to manage (e.g. when the\n // items aren't being collected via `ViewChildren` or `ContentChildren`).\n if (items instanceof QueryList) {\n this._items = items.toArray();\n items.changes.subscribe(newItems => {\n this._items = newItems.toArray();\n this._typeahead?.setItems(this._items);\n this._updateActiveItemIndex(this._items);\n this._initializeFocus();\n });\n } else if (isObservable(items)) {\n items.subscribe(newItems => {\n this._items = newItems;\n this._typeahead?.setItems(newItems);\n this._updateActiveItemIndex(newItems);\n this._initializeFocus();\n });\n } else {\n this._items = items;\n this._initializeFocus();\n }\n if (typeof config.shouldActivationFollowFocus === 'boolean') {\n this._shouldActivationFollowFocus = config.shouldActivationFollowFocus;\n }\n if (config.horizontalOrientation) {\n this._horizontalOrientation = config.horizontalOrientation;\n }\n if (config.skipPredicate) {\n this._skipPredicateFn = config.skipPredicate;\n }\n if (config.trackBy) {\n this._trackByFn = config.trackBy;\n }\n if (typeof config.typeAheadDebounceInterval !== 'undefined') {\n this._setTypeAhead(config.typeAheadDebounceInterval);\n }\n }\n /** Stream that emits any time the focused item changes. */\n change = /*#__PURE__*/new Subject();\n /** Cleans up the key manager. */\n destroy() {\n this._typeaheadSubscription.unsubscribe();\n this._typeahead?.destroy();\n this.change.complete();\n }\n /**\n * Handles a keyboard event on the tree.\n * @param event Keyboard event that represents the user interaction with the tree.\n */\n onKeydown(event) {\n const key = event.key;\n switch (key) {\n case 'Tab':\n // Return early here, in order to allow Tab to actually tab out of the tree\n return;\n case 'ArrowDown':\n this._focusNextItem();\n break;\n case 'ArrowUp':\n this._focusPreviousItem();\n break;\n case 'ArrowRight':\n this._horizontalOrientation === 'rtl' ? this._collapseCurrentItem() : this._expandCurrentItem();\n break;\n case 'ArrowLeft':\n this._horizontalOrientation === 'rtl' ? this._expandCurrentItem() : this._collapseCurrentItem();\n break;\n case 'Home':\n this._focusFirstItem();\n break;\n case 'End':\n this._focusLastItem();\n break;\n case 'Enter':\n case ' ':\n this._activateCurrentItem();\n break;\n default:\n if (event.key === '*') {\n this._expandAllItemsAtCurrentItemLevel();\n break;\n }\n this._typeahead?.handleKey(event);\n // Return here, in order to avoid preventing the default action of non-navigational\n // keys or resetting the buffer of pressed letters.\n return;\n }\n // Reset the typeahead since the user has used a navigational key.\n this._typeahead?.reset();\n event.preventDefault();\n }\n /** Index of the currently active item. */\n getActiveItemIndex() {\n return this._activeItemIndex;\n }\n /** The currently active item. */\n getActiveItem() {\n return this._activeItem;\n }\n /** Focus the first available item. */\n _focusFirstItem() {\n this.focusItem(this._findNextAvailableItemIndex(-1));\n }\n /** Focus the last available item. */\n _focusLastItem() {\n this.focusItem(this._findPreviousAvailableItemIndex(this._items.length));\n }\n /** Focus the next available item. */\n _focusNextItem() {\n this.focusItem(this._findNextAvailableItemIndex(this._activeItemIndex));\n }\n /** Focus the previous available item. */\n _focusPreviousItem() {\n this.focusItem(this._findPreviousAvailableItemIndex(this._activeItemIndex));\n }\n focusItem(itemOrIndex, options = {}) {\n // Set default options\n options.emitChangeEvent ??= true;\n let index = typeof itemOrIndex === 'number' ? itemOrIndex : this._items.findIndex(item => this._trackByFn(item) === this._trackByFn(itemOrIndex));\n if (index < 0 || index >= this._items.length) {\n return;\n }\n const activeItem = this._items[index];\n // If we're just setting the same item, don't re-call activate or focus\n if (this._activeItem !== null && this._trackByFn(activeItem) === this._trackByFn(this._activeItem)) {\n return;\n }\n const previousActiveItem = this._activeItem;\n this._activeItem = activeItem ?? null;\n this._activeItemIndex = index;\n this._typeahead?.setCurrentSelectedItemIndex(index);\n this._activeItem?.focus();\n previousActiveItem?.unfocus();\n if (options.emitChangeEvent) {\n this.change.next(this._activeItem);\n }\n if (this._shouldActivationFollowFocus) {\n this._activateCurrentItem();\n }\n }\n _updateActiveItemIndex(newItems) {\n const activeItem = this._activeItem;\n if (!activeItem) {\n return;\n }\n const newIndex = newItems.findIndex(item => this._trackByFn(item) === this._trackByFn(activeItem));\n if (newIndex > -1 && newIndex !== this._activeItemIndex) {\n this._activeItemIndex = newIndex;\n this._typeahead?.setCurrentSelectedItemIndex(newIndex);\n }\n }\n _setTypeAhead(debounceInterval) {\n this._typeahead = new Typeahead(this._items, {\n debounceInterval: typeof debounceInterval === 'number' ? debounceInterval : undefined,\n skipPredicate: item => this._skipPredicateFn(item)\n });\n this._typeaheadSubscription = this._typeahead.selectedItem.subscribe(item => {\n this.focusItem(item);\n });\n }\n _findNextAvailableItemIndex(startingIndex) {\n for (let i = startingIndex + 1; i < this._items.length; i++) {\n if (!this._skipPredicateFn(this._items[i])) {\n return i;\n }\n }\n return startingIndex;\n }\n _findPreviousAvailableItemIndex(startingIndex) {\n for (let i = startingIndex - 1; i >= 0; i--) {\n if (!this._skipPredicateFn(this._items[i])) {\n return i;\n }\n }\n return startingIndex;\n }\n /**\n * If the item is already expanded, we collapse the item. Otherwise, we will focus the parent.\n */\n _collapseCurrentItem() {\n if (!this._activeItem) {\n return;\n }\n if (this._isCurrentItemExpanded()) {\n this._activeItem.collapse();\n } else {\n const parent = this._activeItem.getParent();\n if (!parent || this._skipPredicateFn(parent)) {\n return;\n }\n this.focusItem(parent);\n }\n }\n /**\n * If the item is already collapsed, we expand the item. Otherwise, we will focus the first child.\n */\n _expandCurrentItem() {\n if (!this._activeItem) {\n return;\n }\n if (!this._isCurrentItemExpanded()) {\n this._activeItem.expand();\n } else {\n coerceObservable(this._activeItem.getChildren()).pipe(take(1)).subscribe(children => {\n const firstChild = children.find(child => !this._skipPredicateFn(child));\n if (!firstChild) {\n return;\n }\n this.focusItem(firstChild);\n });\n }\n }\n _isCurrentItemExpanded() {\n if (!this._activeItem) {\n return false;\n }\n return typeof this._activeItem.isExpanded === 'boolean' ? this._activeItem.isExpanded : this._activeItem.isExpanded();\n }\n _isItemDisabled(item) {\n return typeof item.isDisabled === 'boolean' ? item.isDisabled : item.isDisabled?.();\n }\n /** For all items that are the same level as the current item, we expand those items. */\n _expandAllItemsAtCurrentItemLevel() {\n if (!this._activeItem) {\n return;\n }\n const parent = this._activeItem.getParent();\n let itemsToExpand;\n if (!parent) {\n itemsToExpand = of(this._items.filter(item => item.getParent() === null));\n } else {\n itemsToExpand = coerceObservable(parent.getChildren());\n }\n itemsToExpand.pipe(take(1)).subscribe(items => {\n for (const item of items) {\n item.expand();\n }\n });\n }\n _activateCurrentItem() {\n this._activeItem?.activate();\n }\n}\n/** @docs-private */\nfunction TREE_KEY_MANAGER_FACTORY() {\n return (items, options) => new TreeKeyManager(items, options);\n}\n/** Injection token that determines the key manager to use. */\nconst TREE_KEY_MANAGER = /*#__PURE__*/new InjectionToken('tree-key-manager', {\n providedIn: 'root',\n factory: TREE_KEY_MANAGER_FACTORY\n});\n/** @docs-private */\nconst TREE_KEY_MANAGER_FACTORY_PROVIDER = {\n provide: TREE_KEY_MANAGER,\n useFactory: TREE_KEY_MANAGER_FACTORY\n};\n\n// NoopTreeKeyManager is a \"noop\" implementation of TreeKeyMangerStrategy. Methods are noops. Does\n// not emit to streams.\n//\n// Used for applications built before TreeKeyManager to opt-out of TreeKeyManager and revert to\n// legacy behavior.\n/**\n * @docs-private\n *\n * Opt-out of Tree of key manager behavior.\n *\n * When provided, Tree has same focus management behavior as before TreeKeyManager was introduced.\n * - Tree does not respond to keyboard interaction\n * - Tree node allows tabindex to be set by Input binding\n * - Tree node allows tabindex to be set by attribute binding\n *\n * @deprecated NoopTreeKeyManager deprecated. Use TreeKeyManager or inject a\n * TreeKeyManagerStrategy instead. To be removed in a future version.\n *\n * @breaking-change 21.0.0\n */\nclass NoopTreeKeyManager {\n _isNoopTreeKeyManager = true;\n // Provide change as required by TreeKeyManagerStrategy. NoopTreeKeyManager is a \"noop\"\n // implementation that does not emit to streams.\n change = /*#__PURE__*/new Subject();\n destroy() {\n this.change.complete();\n }\n onKeydown() {\n // noop\n }\n getActiveItemIndex() {\n // Always return null. NoopTreeKeyManager is a \"noop\" implementation that does not maintain\n // the active item.\n return null;\n }\n getActiveItem() {\n // Always return null. NoopTreeKeyManager is a \"noop\" implementation that does not maintain\n // the active item.\n return null;\n }\n focusItem() {\n // noop\n }\n}\n/**\n * @docs-private\n *\n * Opt-out of Tree of key manager behavior.\n *\n * When provided, Tree has same focus management behavior as before TreeKeyManager was introduced.\n * - Tree does not respond to keyboard interaction\n * - Tree node allows tabindex to be set by Input binding\n * - Tree node allows tabindex to be set by attribute binding\n *\n * @deprecated NoopTreeKeyManager deprecated. Use TreeKeyManager or inject a\n * TreeKeyManagerStrategy instead. To be removed in a future version.\n *\n * @breaking-change 21.0.0\n */\nfunction NOOP_TREE_KEY_MANAGER_FACTORY() {\n return () => new NoopTreeKeyManager();\n}\n/**\n * @docs-private\n *\n * Opt-out of Tree of key manager behavior.\n *\n * When provided, Tree has same focus management behavior as before TreeKeyManager was introduced.\n * - Tree does not respond to keyboard interaction\n * - Tree node allows tabindex to be set by Input binding\n * - Tree node allows tabindex to be set by attribute binding\n *\n * @deprecated NoopTreeKeyManager deprecated. Use TreeKeyManager or inject a\n * TreeKeyManagerStrategy instead. To be removed in a future version.\n *\n * @breaking-change 21.0.0\n */\nconst NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER = {\n provide: TREE_KEY_MANAGER,\n useFactory: NOOP_TREE_KEY_MANAGER_FACTORY\n};\n\n/**\n * Configuration for the isFocusable method.\n */\nclass IsFocusableConfig {\n /**\n * Whether to count an element as focusable even if it is not currently visible.\n */\n ignoreVisibility = false;\n}\n// The InteractivityChecker leans heavily on the ally.js accessibility utilities.\n// Methods like `isTabbable` are only covering specific edge-cases for the browsers which are\n// supported.\n/**\n * Utility for checking the interactivity of an element, such as whether it is focusable or\n * tabbable.\n */\nlet InteractivityChecker = /*#__PURE__*/(() => {\n class InteractivityChecker {\n _platform = inject(Platform);\n constructor() {}\n /**\n * Gets whether an element is disabled.\n *\n * @param element Element to be checked.\n * @returns Whether the element is disabled.\n */\n isDisabled(element) {\n // This does not capture some cases, such as a non-form control with a disabled attribute or\n // a form control inside of a disabled form, but should capture the most common cases.\n return element.hasAttribute('disabled');\n }\n /**\n * Gets whether an element is visible for the purposes of interactivity.\n *\n * This will capture states like `display: none` and `visibility: hidden`, but not things like\n * being clipped by an `overflow: hidden` parent or being outside the viewport.\n *\n * @returns Whether the element is visible.\n */\n isVisible(element) {\n return hasGeometry(element) && getComputedStyle(element).visibility === 'visible';\n }\n /**\n * Gets whether an element can be reached via Tab key.\n * Assumes that the element has already been checked with isFocusable.\n *\n * @param element Element to be checked.\n * @returns Whether the element is tabbable.\n */\n isTabbable(element) {\n // Nothing is tabbable on the server 😎\n if (!this._platform.isBrowser) {\n return false;\n }\n const frameElement = getFrameElement(getWindow(element));\n if (frameElement) {\n // Frame elements inherit their tabindex onto all child elements.\n if (getTabIndexValue(frameElement) === -1) {\n return false;\n }\n // Browsers disable tabbing to an element inside of an invisible frame.\n if (!this.isVisible(frameElement)) {\n return false;\n }\n }\n let nodeName = element.nodeName.toLowerCase();\n let tabIndexValue = getTabIndexValue(element);\n if (element.hasAttribute('contenteditable')) {\n return tabIndexValue !== -1;\n }\n if (nodeName === 'iframe' || nodeName === 'object') {\n // The frame or object's content may be tabbable depending on the content, but it's\n // not possibly to reliably detect the content of the frames. We always consider such\n // elements as non-tabbable.\n return false;\n }\n // In iOS, the browser only considers some specific elements as tabbable.\n if (this._platform.WEBKIT && this._platform.IOS && !isPotentiallyTabbableIOS(element)) {\n return false;\n }\n if (nodeName === 'audio') {\n // Audio elements without controls enabled are never tabbable, regardless\n // of the tabindex attribute explicitly being set.\n if (!element.hasAttribute('controls')) {\n return false;\n }\n // Audio elements with controls are by default tabbable unless the\n // tabindex attribute is set to `-1` explicitly.\n return tabIndexValue !== -1;\n }\n if (nodeName === 'video') {\n // For all video elements, if the tabindex attribute is set to `-1`, the video\n // is not tabbable. Note: We cannot rely on the default `HTMLElement.tabIndex`\n // property as that one is set to `-1` in Chrome, Edge and Safari v13.1. The\n // tabindex attribute is the source of truth here.\n if (tabIndexValue === -1) {\n return false;\n }\n // If the tabindex is explicitly set, and not `-1` (as per check before), the\n // video element is always tabbable (regardless of whether it has controls or not).\n if (tabIndexValue !== null) {\n return true;\n }\n // Otherwise (when no explicit tabindex is set), a video is only tabbable if it\n // has controls enabled. Firefox is special as videos are always tabbable regardless\n // of whether there are controls or not.\n return this._platform.FIREFOX || element.hasAttribute('controls');\n }\n return element.tabIndex >= 0;\n }\n /**\n * Gets whether an element can be focused by the user.\n *\n * @param element Element to be checked.\n * @param config The config object with options to customize this method's behavior\n * @returns Whether the element is focusable.\n */\n isFocusable(element, config) {\n // Perform checks in order of left to most expensive.\n // Again, naive approach that does not capture many edge cases and browser quirks.\n return isPotentiallyFocusable(element) && !this.isDisabled(element) && (config?.ignoreVisibility || this.isVisible(element));\n }\n static ɵfac = function InteractivityChecker_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || InteractivityChecker)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: InteractivityChecker,\n factory: InteractivityChecker.ɵfac,\n providedIn: 'root'\n });\n }\n return InteractivityChecker;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Returns the frame element from a window object. Since browsers like MS Edge throw errors if\n * the frameElement property is being accessed from a different host address, this property\n * should be accessed carefully.\n */\nfunction getFrameElement(window) {\n try {\n return window.frameElement;\n } catch {\n return null;\n }\n}\n/** Checks whether the specified element has any geometry / rectangles. */\nfunction hasGeometry(element) {\n // Use logic from jQuery to check for an invisible element.\n // See https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js#L12\n return !!(element.offsetWidth || element.offsetHeight || typeof element.getClientRects === 'function' && element.getClientRects().length);\n}\n/** Gets whether an element's */\nfunction isNativeFormElement(element) {\n let nodeName = element.nodeName.toLowerCase();\n return nodeName === 'input' || nodeName === 'select' || nodeName === 'button' || nodeName === 'textarea';\n}\n/** Gets whether an element is an ``. */\nfunction isHiddenInput(element) {\n return isInputElement(element) && element.type == 'hidden';\n}\n/** Gets whether an element is an anchor that has an href attribute. */\nfunction isAnchorWithHref(element) {\n return isAnchorElement(element) && element.hasAttribute('href');\n}\n/** Gets whether an element is an input element. */\nfunction isInputElement(element) {\n return element.nodeName.toLowerCase() == 'input';\n}\n/** Gets whether an element is an anchor element. */\nfunction isAnchorElement(element) {\n return element.nodeName.toLowerCase() == 'a';\n}\n/** Gets whether an element has a valid tabindex. */\nfunction hasValidTabIndex(element) {\n if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {\n return false;\n }\n let tabIndex = element.getAttribute('tabindex');\n return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));\n}\n/**\n * Returns the parsed tabindex from the element attributes instead of returning the\n * evaluated tabindex from the browsers defaults.\n */\nfunction getTabIndexValue(element) {\n if (!hasValidTabIndex(element)) {\n return null;\n }\n // See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054\n const tabIndex = parseInt(element.getAttribute('tabindex') || '', 10);\n return isNaN(tabIndex) ? -1 : tabIndex;\n}\n/** Checks whether the specified element is potentially tabbable on iOS */\nfunction isPotentiallyTabbableIOS(element) {\n let nodeName = element.nodeName.toLowerCase();\n let inputType = nodeName === 'input' && element.type;\n return inputType === 'text' || inputType === 'password' || nodeName === 'select' || nodeName === 'textarea';\n}\n/**\n * Gets whether an element is potentially focusable without taking current visible/disabled state\n * into account.\n */\nfunction isPotentiallyFocusable(element) {\n // Inputs are potentially focusable *unless* they're type=\"hidden\".\n if (isHiddenInput(element)) {\n return false;\n }\n return isNativeFormElement(element) || isAnchorWithHref(element) || element.hasAttribute('contenteditable') || hasValidTabIndex(element);\n}\n/** Gets the parent window of a DOM node with regards of being inside of an iframe. */\nfunction getWindow(node) {\n // ownerDocument is null if `node` itself *is* a document.\n return node.ownerDocument && node.ownerDocument.defaultView || window;\n}\n\n/**\n * Class that allows for trapping focus within a DOM element.\n *\n * This class currently uses a relatively simple approach to focus trapping.\n * It assumes that the tab order is the same as DOM order, which is not necessarily true.\n * Things like `tabIndex > 0`, flex `order`, and shadow roots can cause the two to be misaligned.\n */\nclass FocusTrap {\n _element;\n _checker;\n _ngZone;\n _document;\n _injector;\n _startAnchor;\n _endAnchor;\n _hasAttached = false;\n // Event listeners for the anchors. Need to be regular functions so that we can unbind them later.\n startAnchorListener = () => this.focusLastTabbableElement();\n endAnchorListener = () => this.focusFirstTabbableElement();\n /** Whether the focus trap is active. */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n this._enabled = value;\n if (this._startAnchor && this._endAnchor) {\n this._toggleAnchorTabIndex(value, this._startAnchor);\n this._toggleAnchorTabIndex(value, this._endAnchor);\n }\n }\n _enabled = true;\n constructor(_element, _checker, _ngZone, _document, deferAnchors = false, /** @breaking-change 20.0.0 param to become required */\n _injector) {\n this._element = _element;\n this._checker = _checker;\n this._ngZone = _ngZone;\n this._document = _document;\n this._injector = _injector;\n if (!deferAnchors) {\n this.attachAnchors();\n }\n }\n /** Destroys the focus trap by cleaning up the anchors. */\n destroy() {\n const startAnchor = this._startAnchor;\n const endAnchor = this._endAnchor;\n if (startAnchor) {\n startAnchor.removeEventListener('focus', this.startAnchorListener);\n startAnchor.remove();\n }\n if (endAnchor) {\n endAnchor.removeEventListener('focus', this.endAnchorListener);\n endAnchor.remove();\n }\n this._startAnchor = this._endAnchor = null;\n this._hasAttached = false;\n }\n /**\n * Inserts the anchors into the DOM. This is usually done automatically\n * in the constructor, but can be deferred for cases like directives with `*ngIf`.\n * @returns Whether the focus trap managed to attach successfully. This may not be the case\n * if the target element isn't currently in the DOM.\n */\n attachAnchors() {\n // If we're not on the browser, there can be no focus to trap.\n if (this._hasAttached) {\n return true;\n }\n this._ngZone.runOutsideAngular(() => {\n if (!this._startAnchor) {\n this._startAnchor = this._createAnchor();\n this._startAnchor.addEventListener('focus', this.startAnchorListener);\n }\n if (!this._endAnchor) {\n this._endAnchor = this._createAnchor();\n this._endAnchor.addEventListener('focus', this.endAnchorListener);\n }\n });\n if (this._element.parentNode) {\n this._element.parentNode.insertBefore(this._startAnchor, this._element);\n this._element.parentNode.insertBefore(this._endAnchor, this._element.nextSibling);\n this._hasAttached = true;\n }\n return this._hasAttached;\n }\n /**\n * Waits for the zone to stabilize, then focuses the first tabbable element.\n * @returns Returns a promise that resolves with a boolean, depending\n * on whether focus was moved successfully.\n */\n focusInitialElementWhenReady(options) {\n return new Promise(resolve => {\n this._executeOnStable(() => resolve(this.focusInitialElement(options)));\n });\n }\n /**\n * Waits for the zone to stabilize, then focuses\n * the first tabbable element within the focus trap region.\n * @returns Returns a promise that resolves with a boolean, depending\n * on whether focus was moved successfully.\n */\n focusFirstTabbableElementWhenReady(options) {\n return new Promise(resolve => {\n this._executeOnStable(() => resolve(this.focusFirstTabbableElement(options)));\n });\n }\n /**\n * Waits for the zone to stabilize, then focuses\n * the last tabbable element within the focus trap region.\n * @returns Returns a promise that resolves with a boolean, depending\n * on whether focus was moved successfully.\n */\n focusLastTabbableElementWhenReady(options) {\n return new Promise(resolve => {\n this._executeOnStable(() => resolve(this.focusLastTabbableElement(options)));\n });\n }\n /**\n * Get the specified boundary element of the trapped region.\n * @param bound The boundary to get (start or end of trapped region).\n * @returns The boundary element.\n */\n _getRegionBoundary(bound) {\n // Contains the deprecated version of selector, for temporary backwards comparability.\n const markers = this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` + `[cdkFocusRegion${bound}], ` + `[cdk-focus-${bound}]`);\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n for (let i = 0; i < markers.length; i++) {\n // @breaking-change 8.0.0\n if (markers[i].hasAttribute(`cdk-focus-${bound}`)) {\n console.warn(`Found use of deprecated attribute 'cdk-focus-${bound}', ` + `use 'cdkFocusRegion${bound}' instead. The deprecated ` + `attribute will be removed in 8.0.0.`, markers[i]);\n } else if (markers[i].hasAttribute(`cdk-focus-region-${bound}`)) {\n console.warn(`Found use of deprecated attribute 'cdk-focus-region-${bound}', ` + `use 'cdkFocusRegion${bound}' instead. The deprecated attribute ` + `will be removed in 8.0.0.`, markers[i]);\n }\n }\n }\n if (bound == 'start') {\n return markers.length ? markers[0] : this._getFirstTabbableElement(this._element);\n }\n return markers.length ? markers[markers.length - 1] : this._getLastTabbableElement(this._element);\n }\n /**\n * Focuses the element that should be focused when the focus trap is initialized.\n * @returns Whether focus was moved successfully.\n */\n focusInitialElement(options) {\n // Contains the deprecated version of selector, for temporary backwards comparability.\n const redirectToElement = this._element.querySelector(`[cdk-focus-initial], ` + `[cdkFocusInitial]`);\n if (redirectToElement) {\n // @breaking-change 8.0.0\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && redirectToElement.hasAttribute(`cdk-focus-initial`)) {\n console.warn(`Found use of deprecated attribute 'cdk-focus-initial', ` + `use 'cdkFocusInitial' instead. The deprecated attribute ` + `will be removed in 8.0.0`, redirectToElement);\n }\n // Warn the consumer if the element they've pointed to\n // isn't focusable, when not in production mode.\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && !this._checker.isFocusable(redirectToElement)) {\n console.warn(`Element matching '[cdkFocusInitial]' is not focusable.`, redirectToElement);\n }\n if (!this._checker.isFocusable(redirectToElement)) {\n const focusableChild = this._getFirstTabbableElement(redirectToElement);\n focusableChild?.focus(options);\n return !!focusableChild;\n }\n redirectToElement.focus(options);\n return true;\n }\n return this.focusFirstTabbableElement(options);\n }\n /**\n * Focuses the first tabbable element within the focus trap region.\n * @returns Whether focus was moved successfully.\n */\n focusFirstTabbableElement(options) {\n const redirectToElement = this._getRegionBoundary('start');\n if (redirectToElement) {\n redirectToElement.focus(options);\n }\n return !!redirectToElement;\n }\n /**\n * Focuses the last tabbable element within the focus trap region.\n * @returns Whether focus was moved successfully.\n */\n focusLastTabbableElement(options) {\n const redirectToElement = this._getRegionBoundary('end');\n if (redirectToElement) {\n redirectToElement.focus(options);\n }\n return !!redirectToElement;\n }\n /**\n * Checks whether the focus trap has successfully been attached.\n */\n hasAttached() {\n return this._hasAttached;\n }\n /** Get the first tabbable element from a DOM subtree (inclusive). */\n _getFirstTabbableElement(root) {\n if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {\n return root;\n }\n const children = root.children;\n for (let i = 0; i < children.length; i++) {\n const tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE ? this._getFirstTabbableElement(children[i]) : null;\n if (tabbableChild) {\n return tabbableChild;\n }\n }\n return null;\n }\n /** Get the last tabbable element from a DOM subtree (inclusive). */\n _getLastTabbableElement(root) {\n if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {\n return root;\n }\n // Iterate in reverse DOM order.\n const children = root.children;\n for (let i = children.length - 1; i >= 0; i--) {\n const tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE ? this._getLastTabbableElement(children[i]) : null;\n if (tabbableChild) {\n return tabbableChild;\n }\n }\n return null;\n }\n /** Creates an anchor element. */\n _createAnchor() {\n const anchor = this._document.createElement('div');\n this._toggleAnchorTabIndex(this._enabled, anchor);\n anchor.classList.add('cdk-visually-hidden');\n anchor.classList.add('cdk-focus-trap-anchor');\n anchor.setAttribute('aria-hidden', 'true');\n return anchor;\n }\n /**\n * Toggles the `tabindex` of an anchor, based on the enabled state of the focus trap.\n * @param isEnabled Whether the focus trap is enabled.\n * @param anchor Anchor on which to toggle the tabindex.\n */\n _toggleAnchorTabIndex(isEnabled, anchor) {\n // Remove the tabindex completely, rather than setting it to -1, because if the\n // element has a tabindex, the user might still hit it when navigating with the arrow keys.\n isEnabled ? anchor.setAttribute('tabindex', '0') : anchor.removeAttribute('tabindex');\n }\n /**\n * Toggles the`tabindex` of both anchors to either trap Tab focus or allow it to escape.\n * @param enabled: Whether the anchors should trap Tab.\n */\n toggleAnchors(enabled) {\n if (this._startAnchor && this._endAnchor) {\n this._toggleAnchorTabIndex(enabled, this._startAnchor);\n this._toggleAnchorTabIndex(enabled, this._endAnchor);\n }\n }\n /** Executes a function when the zone is stable. */\n _executeOnStable(fn) {\n // TODO: remove this conditional when injector is required in the constructor.\n if (this._injector) {\n afterNextRender(fn, {\n injector: this._injector\n });\n } else {\n setTimeout(fn);\n }\n }\n}\n/**\n * Factory that allows easy instantiation of focus traps.\n */\nlet FocusTrapFactory = /*#__PURE__*/(() => {\n class FocusTrapFactory {\n _checker = inject(InteractivityChecker);\n _ngZone = inject(NgZone);\n _document = inject(DOCUMENT);\n _injector = inject(Injector);\n constructor() {\n inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);\n }\n /**\n * Creates a focus-trapped region around the given element.\n * @param element The element around which focus will be trapped.\n * @param deferCaptureElements Defers the creation of focus-capturing elements to be done\n * manually by the user.\n * @returns The created focus trap instance.\n */\n create(element, deferCaptureElements = false) {\n return new FocusTrap(element, this._checker, this._ngZone, this._document, deferCaptureElements, this._injector);\n }\n static ɵfac = function FocusTrapFactory_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || FocusTrapFactory)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: FocusTrapFactory,\n factory: FocusTrapFactory.ɵfac,\n providedIn: 'root'\n });\n }\n return FocusTrapFactory;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/** Directive for trapping focus within a region. */\nlet CdkTrapFocus = /*#__PURE__*/(() => {\n class CdkTrapFocus {\n _elementRef = inject(ElementRef);\n _focusTrapFactory = inject(FocusTrapFactory);\n /** Underlying FocusTrap instance. */\n focusTrap;\n /** Previously focused element to restore focus to upon destroy when using autoCapture. */\n _previouslyFocusedElement = null;\n /** Whether the focus trap is active. */\n get enabled() {\n return this.focusTrap?.enabled || false;\n }\n set enabled(value) {\n if (this.focusTrap) {\n this.focusTrap.enabled = value;\n }\n }\n /**\n * Whether the directive should automatically move focus into the trapped region upon\n * initialization and return focus to the previous activeElement upon destruction.\n */\n autoCapture;\n constructor() {\n const platform = inject(Platform);\n if (platform.isBrowser) {\n this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);\n }\n }\n ngOnDestroy() {\n this.focusTrap?.destroy();\n // If we stored a previously focused element when using autoCapture, return focus to that\n // element now that the trapped region is being destroyed.\n if (this._previouslyFocusedElement) {\n this._previouslyFocusedElement.focus();\n this._previouslyFocusedElement = null;\n }\n }\n ngAfterContentInit() {\n this.focusTrap?.attachAnchors();\n if (this.autoCapture) {\n this._captureFocus();\n }\n }\n ngDoCheck() {\n if (this.focusTrap && !this.focusTrap.hasAttached()) {\n this.focusTrap.attachAnchors();\n }\n }\n ngOnChanges(changes) {\n const autoCaptureChange = changes['autoCapture'];\n if (autoCaptureChange && !autoCaptureChange.firstChange && this.autoCapture && this.focusTrap?.hasAttached()) {\n this._captureFocus();\n }\n }\n _captureFocus() {\n this._previouslyFocusedElement = _getFocusedElementPierceShadowDom();\n this.focusTrap?.focusInitialElementWhenReady();\n }\n static ɵfac = function CdkTrapFocus_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || CdkTrapFocus)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: CdkTrapFocus,\n selectors: [[\"\", \"cdkTrapFocus\", \"\"]],\n inputs: {\n enabled: [2, \"cdkTrapFocus\", \"enabled\", booleanAttribute],\n autoCapture: [2, \"cdkTrapFocusAutoCapture\", \"autoCapture\", booleanAttribute]\n },\n exportAs: [\"cdkTrapFocus\"],\n features: [i0.ɵɵInputTransformsFeature, i0.ɵɵNgOnChangesFeature]\n });\n }\n return CdkTrapFocus;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Class that allows for trapping focus within a DOM element.\n *\n * This class uses a strategy pattern that determines how it traps focus.\n * See FocusTrapInertStrategy.\n */\nclass ConfigurableFocusTrap extends FocusTrap {\n _focusTrapManager;\n _inertStrategy;\n /** Whether the FocusTrap is enabled. */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n this._enabled = value;\n if (this._enabled) {\n this._focusTrapManager.register(this);\n } else {\n this._focusTrapManager.deregister(this);\n }\n }\n constructor(_element, _checker, _ngZone, _document, _focusTrapManager, _inertStrategy, config, injector) {\n super(_element, _checker, _ngZone, _document, config.defer, injector);\n this._focusTrapManager = _focusTrapManager;\n this._inertStrategy = _inertStrategy;\n this._focusTrapManager.register(this);\n }\n /** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */\n destroy() {\n this._focusTrapManager.deregister(this);\n super.destroy();\n }\n /** @docs-private Implemented as part of ManagedFocusTrap. */\n _enable() {\n this._inertStrategy.preventFocus(this);\n this.toggleAnchors(true);\n }\n /** @docs-private Implemented as part of ManagedFocusTrap. */\n _disable() {\n this._inertStrategy.allowFocus(this);\n this.toggleAnchors(false);\n }\n}\n\n/**\n * Lightweight FocusTrapInertStrategy that adds a document focus event\n * listener to redirect focus back inside the FocusTrap.\n */\nclass EventListenerFocusTrapInertStrategy {\n /** Focus event handler. */\n _listener = null;\n /** Adds a document event listener that keeps focus inside the FocusTrap. */\n preventFocus(focusTrap) {\n // Ensure there's only one listener per document\n if (this._listener) {\n focusTrap._document.removeEventListener('focus', this._listener, true);\n }\n this._listener = e => this._trapFocus(focusTrap, e);\n focusTrap._ngZone.runOutsideAngular(() => {\n focusTrap._document.addEventListener('focus', this._listener, true);\n });\n }\n /** Removes the event listener added in preventFocus. */\n allowFocus(focusTrap) {\n if (!this._listener) {\n return;\n }\n focusTrap._document.removeEventListener('focus', this._listener, true);\n this._listener = null;\n }\n /**\n * Refocuses the first element in the FocusTrap if the focus event target was outside\n * the FocusTrap.\n *\n * This is an event listener callback. The event listener is added in runOutsideAngular,\n * so all this code runs outside Angular as well.\n */\n _trapFocus(focusTrap, event) {\n const target = event.target;\n const focusTrapRoot = focusTrap._element;\n // Don't refocus if target was in an overlay, because the overlay might be associated\n // with an element inside the FocusTrap, ex. mat-select.\n if (target && !focusTrapRoot.contains(target) && !target.closest?.('div.cdk-overlay-pane')) {\n // Some legacy FocusTrap usages have logic that focuses some element on the page\n // just before FocusTrap is destroyed. For backwards compatibility, wait\n // to be sure FocusTrap is still enabled before refocusing.\n setTimeout(() => {\n // Check whether focus wasn't put back into the focus trap while the timeout was pending.\n if (focusTrap.enabled && !focusTrapRoot.contains(focusTrap._document.activeElement)) {\n focusTrap.focusFirstTabbableElement();\n }\n });\n }\n }\n}\n\n/** The injection token used to specify the inert strategy. */\nconst FOCUS_TRAP_INERT_STRATEGY = /*#__PURE__*/new InjectionToken('FOCUS_TRAP_INERT_STRATEGY');\n\n/** Injectable that ensures only the most recently enabled FocusTrap is active. */\nlet FocusTrapManager = /*#__PURE__*/(() => {\n class FocusTrapManager {\n // A stack of the FocusTraps on the page. Only the FocusTrap at the\n // top of the stack is active.\n _focusTrapStack = [];\n /**\n * Disables the FocusTrap at the top of the stack, and then pushes\n * the new FocusTrap onto the stack.\n */\n register(focusTrap) {\n // Dedupe focusTraps that register multiple times.\n this._focusTrapStack = this._focusTrapStack.filter(ft => ft !== focusTrap);\n let stack = this._focusTrapStack;\n if (stack.length) {\n stack[stack.length - 1]._disable();\n }\n stack.push(focusTrap);\n focusTrap._enable();\n }\n /**\n * Removes the FocusTrap from the stack, and activates the\n * FocusTrap that is the new top of the stack.\n */\n deregister(focusTrap) {\n focusTrap._disable();\n const stack = this._focusTrapStack;\n const i = stack.indexOf(focusTrap);\n if (i !== -1) {\n stack.splice(i, 1);\n if (stack.length) {\n stack[stack.length - 1]._enable();\n }\n }\n }\n static ɵfac = function FocusTrapManager_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || FocusTrapManager)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: FocusTrapManager,\n factory: FocusTrapManager.ɵfac,\n providedIn: 'root'\n });\n }\n return FocusTrapManager;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Factory that allows easy instantiation of configurable focus traps. */\nlet ConfigurableFocusTrapFactory = /*#__PURE__*/(() => {\n class ConfigurableFocusTrapFactory {\n _checker = inject(InteractivityChecker);\n _ngZone = inject(NgZone);\n _focusTrapManager = inject(FocusTrapManager);\n _document = inject(DOCUMENT);\n _inertStrategy;\n _injector = inject(Injector);\n constructor() {\n const inertStrategy = inject(FOCUS_TRAP_INERT_STRATEGY, {\n optional: true\n });\n // TODO split up the strategies into different modules, similar to DateAdapter.\n this._inertStrategy = inertStrategy || new EventListenerFocusTrapInertStrategy();\n }\n create(element, config = {\n defer: false\n }) {\n let configObject;\n if (typeof config === 'boolean') {\n configObject = {\n defer: config\n };\n } else {\n configObject = config;\n }\n return new ConfigurableFocusTrap(element, this._checker, this._ngZone, this._document, this._focusTrapManager, this._inertStrategy, configObject, this._injector);\n }\n static ɵfac = function ConfigurableFocusTrapFactory_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || ConfigurableFocusTrapFactory)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: ConfigurableFocusTrapFactory,\n factory: ConfigurableFocusTrapFactory.ɵfac,\n providedIn: 'root'\n });\n }\n return ConfigurableFocusTrapFactory;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Gets whether an event could be a faked `mousedown` event dispatched by a screen reader. */\nfunction isFakeMousedownFromScreenReader(event) {\n // Some screen readers will dispatch a fake `mousedown` event when pressing enter or space on\n // a clickable element. We can distinguish these events when `event.buttons` is zero, or\n // `event.detail` is zero depending on the browser:\n // - `event.buttons` works on Firefox, but fails on Chrome.\n // - `detail` works on Chrome, but fails on Firefox.\n return event.buttons === 0 || event.detail === 0;\n}\n/** Gets whether an event could be a faked `touchstart` event dispatched by a screen reader. */\nfunction isFakeTouchstartFromScreenReader(event) {\n const touch = event.touches && event.touches[0] || event.changedTouches && event.changedTouches[0];\n // A fake `touchstart` can be distinguished from a real one by looking at the `identifier`\n // which is typically >= 0 on a real device versus -1 from a screen reader. Just to be safe,\n // we can also look at `radiusX` and `radiusY`. This behavior was observed against a Windows 10\n // device with a touch screen running NVDA v2020.4 and Firefox 85 or Chrome 88.\n return !!touch && touch.identifier === -1 && (touch.radiusX == null || touch.radiusX === 1) && (touch.radiusY == null || touch.radiusY === 1);\n}\n\n/**\n * Injectable options for the InputModalityDetector. These are shallowly merged with the default\n * options.\n */\nconst INPUT_MODALITY_DETECTOR_OPTIONS = /*#__PURE__*/new InjectionToken('cdk-input-modality-detector-options');\n/**\n * Default options for the InputModalityDetector.\n *\n * Modifier keys are ignored by default (i.e. when pressed won't cause the service to detect\n * keyboard input modality) for two reasons:\n *\n * 1. Modifier keys are commonly used with mouse to perform actions such as 'right click' or 'open\n * in new tab', and are thus less representative of actual keyboard interaction.\n * 2. VoiceOver triggers some keyboard events when linearly navigating with Control + Option (but\n * confusingly not with Caps Lock). Thus, to have parity with other screen readers, we ignore\n * these keys so as to not update the input modality.\n *\n * Note that we do not by default ignore the right Meta key on Safari because it has the same key\n * code as the ContextMenu key on other browsers. When we switch to using event.key, we can\n * distinguish between the two.\n */\nconst INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS = {\n ignoreKeys: [ALT, CONTROL, MAC_META, META, SHIFT]\n};\n/**\n * The amount of time needed to pass after a touchstart event in order for a subsequent mousedown\n * event to be attributed as mouse and not touch.\n *\n * This is the value used by AngularJS Material. Through trial and error (on iPhone 6S) they found\n * that a value of around 650ms seems appropriate.\n */\nconst TOUCH_BUFFER_MS = 650;\n/**\n * Event listener options that enable capturing and also mark the listener as passive if the browser\n * supports it.\n */\nconst modalityEventListenerOptions = /*#__PURE__*/normalizePassiveListenerOptions({\n passive: true,\n capture: true\n});\n/**\n * Service that detects the user's input modality.\n *\n * This service does not update the input modality when a user navigates with a screen reader\n * (e.g. linear navigation with VoiceOver, object navigation / browse mode with NVDA, virtual PC\n * cursor mode with JAWS). This is in part due to technical limitations (i.e. keyboard events do not\n * fire as expected in these modes) but is also arguably the correct behavior. Navigating with a\n * screen reader is akin to visually scanning a page, and should not be interpreted as actual user\n * input interaction.\n *\n * When a user is not navigating but *interacting* with a screen reader, this service attempts to\n * update the input modality to keyboard, but in general this service's behavior is largely\n * undefined.\n */\nlet InputModalityDetector = /*#__PURE__*/(() => {\n class InputModalityDetector {\n _platform = inject(Platform);\n /** Emits whenever an input modality is detected. */\n modalityDetected;\n /** Emits when the input modality changes. */\n modalityChanged;\n /** The most recently detected input modality. */\n get mostRecentModality() {\n return this._modality.value;\n }\n /**\n * The most recently detected input modality event target. Is null if no input modality has been\n * detected or if the associated event target is null for some unknown reason.\n */\n _mostRecentTarget = null;\n /** The underlying BehaviorSubject that emits whenever an input modality is detected. */\n _modality = new BehaviorSubject(null);\n /** Options for this InputModalityDetector. */\n _options;\n /**\n * The timestamp of the last touch input modality. Used to determine whether mousedown events\n * should be attributed to mouse or touch.\n */\n _lastTouchMs = 0;\n /**\n * Handles keydown events. Must be an arrow function in order to preserve the context when it gets\n * bound.\n */\n _onKeydown = event => {\n // If this is one of the keys we should ignore, then ignore it and don't update the input\n // modality to keyboard.\n if (this._options?.ignoreKeys?.some(keyCode => keyCode === event.keyCode)) {\n return;\n }\n this._modality.next('keyboard');\n this._mostRecentTarget = _getEventTarget(event);\n };\n /**\n * Handles mousedown events. Must be an arrow function in order to preserve the context when it\n * gets bound.\n */\n _onMousedown = event => {\n // Touches trigger both touch and mouse events, so we need to distinguish between mouse events\n // that were triggered via mouse vs touch. To do so, check if the mouse event occurs closely\n // after the previous touch event.\n if (Date.now() - this._lastTouchMs < TOUCH_BUFFER_MS) {\n return;\n }\n // Fake mousedown events are fired by some screen readers when controls are activated by the\n // screen reader. Attribute them to keyboard input modality.\n this._modality.next(isFakeMousedownFromScreenReader(event) ? 'keyboard' : 'mouse');\n this._mostRecentTarget = _getEventTarget(event);\n };\n /**\n * Handles touchstart events. Must be an arrow function in order to preserve the context when it\n * gets bound.\n */\n _onTouchstart = event => {\n // Same scenario as mentioned in _onMousedown, but on touch screen devices, fake touchstart\n // events are fired. Again, attribute to keyboard input modality.\n if (isFakeTouchstartFromScreenReader(event)) {\n this._modality.next('keyboard');\n return;\n }\n // Store the timestamp of this touch event, as it's used to distinguish between mouse events\n // triggered via mouse vs touch.\n this._lastTouchMs = Date.now();\n this._modality.next('touch');\n this._mostRecentTarget = _getEventTarget(event);\n };\n constructor() {\n const ngZone = inject(NgZone);\n const document = inject(DOCUMENT);\n const options = inject(INPUT_MODALITY_DETECTOR_OPTIONS, {\n optional: true\n });\n this._options = {\n ...INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS,\n ...options\n };\n // Skip the first emission as it's null.\n this.modalityDetected = this._modality.pipe(skip(1));\n this.modalityChanged = this.modalityDetected.pipe(distinctUntilChanged());\n // If we're not in a browser, this service should do nothing, as there's no relevant input\n // modality to detect.\n if (this._platform.isBrowser) {\n ngZone.runOutsideAngular(() => {\n document.addEventListener('keydown', this._onKeydown, modalityEventListenerOptions);\n document.addEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);\n document.addEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);\n });\n }\n }\n ngOnDestroy() {\n this._modality.complete();\n if (this._platform.isBrowser) {\n document.removeEventListener('keydown', this._onKeydown, modalityEventListenerOptions);\n document.removeEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);\n document.removeEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);\n }\n }\n static ɵfac = function InputModalityDetector_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || InputModalityDetector)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: InputModalityDetector,\n factory: InputModalityDetector.ɵfac,\n providedIn: 'root'\n });\n }\n return InputModalityDetector;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst LIVE_ANNOUNCER_ELEMENT_TOKEN = /*#__PURE__*/new InjectionToken('liveAnnouncerElement', {\n providedIn: 'root',\n factory: LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY\n});\n/** @docs-private */\nfunction LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY() {\n return null;\n}\n/** Injection token that can be used to configure the default options for the LiveAnnouncer. */\nconst LIVE_ANNOUNCER_DEFAULT_OPTIONS = /*#__PURE__*/new InjectionToken('LIVE_ANNOUNCER_DEFAULT_OPTIONS');\nlet uniqueIds = 0;\nlet LiveAnnouncer = /*#__PURE__*/(() => {\n class LiveAnnouncer {\n _ngZone = inject(NgZone);\n _defaultOptions = inject(LIVE_ANNOUNCER_DEFAULT_OPTIONS, {\n optional: true\n });\n _liveElement;\n _document = inject(DOCUMENT);\n _previousTimeout;\n _currentPromise;\n _currentResolve;\n constructor() {\n const elementToken = inject(LIVE_ANNOUNCER_ELEMENT_TOKEN, {\n optional: true\n });\n this._liveElement = elementToken || this._createLiveElement();\n }\n announce(message, ...args) {\n const defaultOptions = this._defaultOptions;\n let politeness;\n let duration;\n if (args.length === 1 && typeof args[0] === 'number') {\n duration = args[0];\n } else {\n [politeness, duration] = args;\n }\n this.clear();\n clearTimeout(this._previousTimeout);\n if (!politeness) {\n politeness = defaultOptions && defaultOptions.politeness ? defaultOptions.politeness : 'polite';\n }\n if (duration == null && defaultOptions) {\n duration = defaultOptions.duration;\n }\n // TODO: ensure changing the politeness works on all environments we support.\n this._liveElement.setAttribute('aria-live', politeness);\n if (this._liveElement.id) {\n this._exposeAnnouncerToModals(this._liveElement.id);\n }\n // This 100ms timeout is necessary for some browser + screen-reader combinations:\n // - Both JAWS and NVDA over IE11 will not announce anything without a non-zero timeout.\n // - With Chrome and IE11 with NVDA or JAWS, a repeated (identical) message won't be read a\n // second time without clearing and then using a non-zero delay.\n // (using JAWS 17 at time of this writing).\n return this._ngZone.runOutsideAngular(() => {\n if (!this._currentPromise) {\n this._currentPromise = new Promise(resolve => this._currentResolve = resolve);\n }\n clearTimeout(this._previousTimeout);\n this._previousTimeout = setTimeout(() => {\n this._liveElement.textContent = message;\n if (typeof duration === 'number') {\n this._previousTimeout = setTimeout(() => this.clear(), duration);\n }\n // For some reason in tests this can be undefined\n // Probably related to ZoneJS and every other thing that patches browser APIs in tests\n this._currentResolve?.();\n this._currentPromise = this._currentResolve = undefined;\n }, 100);\n return this._currentPromise;\n });\n }\n /**\n * Clears the current text from the announcer element. Can be used to prevent\n * screen readers from reading the text out again while the user is going\n * through the page landmarks.\n */\n clear() {\n if (this._liveElement) {\n this._liveElement.textContent = '';\n }\n }\n ngOnDestroy() {\n clearTimeout(this._previousTimeout);\n this._liveElement?.remove();\n this._liveElement = null;\n this._currentResolve?.();\n this._currentPromise = this._currentResolve = undefined;\n }\n _createLiveElement() {\n const elementClass = 'cdk-live-announcer-element';\n const previousElements = this._document.getElementsByClassName(elementClass);\n const liveEl = this._document.createElement('div');\n // Remove any old containers. This can happen when coming in from a server-side-rendered page.\n for (let i = 0; i < previousElements.length; i++) {\n previousElements[i].remove();\n }\n liveEl.classList.add(elementClass);\n liveEl.classList.add('cdk-visually-hidden');\n liveEl.setAttribute('aria-atomic', 'true');\n liveEl.setAttribute('aria-live', 'polite');\n liveEl.id = `cdk-live-announcer-${uniqueIds++}`;\n this._document.body.appendChild(liveEl);\n return liveEl;\n }\n /**\n * Some browsers won't expose the accessibility node of the live announcer element if there is an\n * `aria-modal` and the live announcer is outside of it. This method works around the issue by\n * pointing the `aria-owns` of all modals to the live announcer element.\n */\n _exposeAnnouncerToModals(id) {\n // TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with\n // the `SnakBarContainer` and other usages.\n //\n // Note that the selector here is limited to CDK overlays at the moment in order to reduce the\n // section of the DOM we need to look through. This should cover all the cases we support, but\n // the selector can be expanded if it turns out to be too narrow.\n const modals = this._document.querySelectorAll('body > .cdk-overlay-container [aria-modal=\"true\"]');\n for (let i = 0; i < modals.length; i++) {\n const modal = modals[i];\n const ariaOwns = modal.getAttribute('aria-owns');\n if (!ariaOwns) {\n modal.setAttribute('aria-owns', id);\n } else if (ariaOwns.indexOf(id) === -1) {\n modal.setAttribute('aria-owns', ariaOwns + ' ' + id);\n }\n }\n }\n static ɵfac = function LiveAnnouncer_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || LiveAnnouncer)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: LiveAnnouncer,\n factory: LiveAnnouncer.ɵfac,\n providedIn: 'root'\n });\n }\n return LiveAnnouncer;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * A directive that works similarly to aria-live, but uses the LiveAnnouncer to ensure compatibility\n * with a wider range of browsers and screen readers.\n */\nlet CdkAriaLive = /*#__PURE__*/(() => {\n class CdkAriaLive {\n _elementRef = inject(ElementRef);\n _liveAnnouncer = inject(LiveAnnouncer);\n _contentObserver = inject(ContentObserver);\n _ngZone = inject(NgZone);\n /** The aria-live politeness level to use when announcing messages. */\n get politeness() {\n return this._politeness;\n }\n set politeness(value) {\n this._politeness = value === 'off' || value === 'assertive' ? value : 'polite';\n if (this._politeness === 'off') {\n if (this._subscription) {\n this._subscription.unsubscribe();\n this._subscription = null;\n }\n } else if (!this._subscription) {\n this._subscription = this._ngZone.runOutsideAngular(() => {\n return this._contentObserver.observe(this._elementRef).subscribe(() => {\n // Note that we use textContent here, rather than innerText, in order to avoid a reflow.\n const elementText = this._elementRef.nativeElement.textContent;\n // The `MutationObserver` fires also for attribute\n // changes which we don't want to announce.\n if (elementText !== this._previousAnnouncedText) {\n this._liveAnnouncer.announce(elementText, this._politeness, this.duration);\n this._previousAnnouncedText = elementText;\n }\n });\n });\n }\n }\n _politeness = 'polite';\n /** Time in milliseconds after which to clear out the announcer element. */\n duration;\n _previousAnnouncedText;\n _subscription;\n constructor() {\n inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);\n }\n ngOnDestroy() {\n if (this._subscription) {\n this._subscription.unsubscribe();\n }\n }\n static ɵfac = function CdkAriaLive_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || CdkAriaLive)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: CdkAriaLive,\n selectors: [[\"\", \"cdkAriaLive\", \"\"]],\n inputs: {\n politeness: [0, \"cdkAriaLive\", \"politeness\"],\n duration: [0, \"cdkAriaLiveDuration\", \"duration\"]\n },\n exportAs: [\"cdkAriaLive\"]\n });\n }\n return CdkAriaLive;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Detection mode used for attributing the origin of a focus event. */\nvar FocusMonitorDetectionMode = /*#__PURE__*/function (FocusMonitorDetectionMode) {\n /**\n * Any mousedown, keydown, or touchstart event that happened in the previous\n * tick or the current tick will be used to assign a focus event's origin (to\n * either mouse, keyboard, or touch). This is the default option.\n */\n FocusMonitorDetectionMode[FocusMonitorDetectionMode[\"IMMEDIATE\"] = 0] = \"IMMEDIATE\";\n /**\n * A focus event's origin is always attributed to the last corresponding\n * mousedown, keydown, or touchstart event, no matter how long ago it occurred.\n */\n FocusMonitorDetectionMode[FocusMonitorDetectionMode[\"EVENTUAL\"] = 1] = \"EVENTUAL\";\n return FocusMonitorDetectionMode;\n}(FocusMonitorDetectionMode || {});\n/** InjectionToken for FocusMonitorOptions. */\nconst FOCUS_MONITOR_DEFAULT_OPTIONS = /*#__PURE__*/new InjectionToken('cdk-focus-monitor-default-options');\n/**\n * Event listener options that enable capturing and also\n * mark the listener as passive if the browser supports it.\n */\nconst captureEventListenerOptions = /*#__PURE__*/normalizePassiveListenerOptions({\n passive: true,\n capture: true\n});\n/** Monitors mouse and keyboard events to determine the cause of focus events. */\nlet FocusMonitor = /*#__PURE__*/(() => {\n class FocusMonitor {\n _ngZone = inject(NgZone);\n _platform = inject(Platform);\n _inputModalityDetector = inject(InputModalityDetector);\n /** The focus origin that the next focus event is a result of. */\n _origin = null;\n /** The FocusOrigin of the last focus event tracked by the FocusMonitor. */\n _lastFocusOrigin;\n /** Whether the window has just been focused. */\n _windowFocused = false;\n /** The timeout id of the window focus timeout. */\n _windowFocusTimeoutId;\n /** The timeout id of the origin clearing timeout. */\n _originTimeoutId;\n /**\n * Whether the origin was determined via a touch interaction. Necessary as properly attributing\n * focus events to touch interactions requires special logic.\n */\n _originFromTouchInteraction = false;\n /** Map of elements being monitored to their info. */\n _elementInfo = new Map();\n /** The number of elements currently being monitored. */\n _monitoredElementCount = 0;\n /**\n * Keeps track of the root nodes to which we've currently bound a focus/blur handler,\n * as well as the number of monitored elements that they contain. We have to treat focus/blur\n * handlers differently from the rest of the events, because the browser won't emit events\n * to the document when focus moves inside of a shadow root.\n */\n _rootNodeFocusListenerCount = new Map();\n /**\n * The specified detection mode, used for attributing the origin of a focus\n * event.\n */\n _detectionMode;\n /**\n * Event listener for `focus` events on the window.\n * Needs to be an arrow function in order to preserve the context when it gets bound.\n */\n _windowFocusListener = () => {\n // Make a note of when the window regains focus, so we can\n // restore the origin info for the focused element.\n this._windowFocused = true;\n this._windowFocusTimeoutId = setTimeout(() => this._windowFocused = false);\n };\n /** Used to reference correct document/window */\n _document = inject(DOCUMENT, {\n optional: true\n });\n /** Subject for stopping our InputModalityDetector subscription. */\n _stopInputModalityDetector = new Subject();\n constructor() {\n const options = inject(FOCUS_MONITOR_DEFAULT_OPTIONS, {\n optional: true\n });\n this._detectionMode = options?.detectionMode || FocusMonitorDetectionMode.IMMEDIATE;\n }\n /**\n * Event listener for `focus` and 'blur' events on the document.\n * Needs to be an arrow function in order to preserve the context when it gets bound.\n */\n _rootNodeFocusAndBlurListener = event => {\n const target = _getEventTarget(event);\n // We need to walk up the ancestor chain in order to support `checkChildren`.\n for (let element = target; element; element = element.parentElement) {\n if (event.type === 'focus') {\n this._onFocus(event, element);\n } else {\n this._onBlur(event, element);\n }\n }\n };\n monitor(element, checkChildren = false) {\n const nativeElement = coerceElement(element);\n // Do nothing if we're not on the browser platform or the passed in node isn't an element.\n if (!this._platform.isBrowser || nativeElement.nodeType !== 1) {\n // Note: we don't want the observable to emit at all so we don't pass any parameters.\n return of();\n }\n // If the element is inside the shadow DOM, we need to bind our focus/blur listeners to\n // the shadow root, rather than the `document`, because the browser won't emit focus events\n // to the `document`, if focus is moving within the same shadow root.\n const rootNode = _getShadowRoot(nativeElement) || this._getDocument();\n const cachedInfo = this._elementInfo.get(nativeElement);\n // Check if we're already monitoring this element.\n if (cachedInfo) {\n if (checkChildren) {\n // TODO(COMP-318): this can be problematic, because it'll turn all non-checkChildren\n // observers into ones that behave as if `checkChildren` was turned on. We need a more\n // robust solution.\n cachedInfo.checkChildren = true;\n }\n return cachedInfo.subject;\n }\n // Create monitored element info.\n const info = {\n checkChildren: checkChildren,\n subject: new Subject(),\n rootNode\n };\n this._elementInfo.set(nativeElement, info);\n this._registerGlobalListeners(info);\n return info.subject;\n }\n stopMonitoring(element) {\n const nativeElement = coerceElement(element);\n const elementInfo = this._elementInfo.get(nativeElement);\n if (elementInfo) {\n elementInfo.subject.complete();\n this._setClasses(nativeElement);\n this._elementInfo.delete(nativeElement);\n this._removeGlobalListeners(elementInfo);\n }\n }\n focusVia(element, origin, options) {\n const nativeElement = coerceElement(element);\n const focusedElement = this._getDocument().activeElement;\n // If the element is focused already, calling `focus` again won't trigger the event listener\n // which means that the focus classes won't be updated. If that's the case, update the classes\n // directly without waiting for an event.\n if (nativeElement === focusedElement) {\n this._getClosestElementsInfo(nativeElement).forEach(([currentElement, info]) => this._originChanged(currentElement, origin, info));\n } else {\n this._setOrigin(origin);\n // `focus` isn't available on the server\n if (typeof nativeElement.focus === 'function') {\n nativeElement.focus(options);\n }\n }\n }\n ngOnDestroy() {\n this._elementInfo.forEach((_info, element) => this.stopMonitoring(element));\n }\n /** Access injected document if available or fallback to global document reference */\n _getDocument() {\n return this._document || document;\n }\n /** Use defaultView of injected document if available or fallback to global window reference */\n _getWindow() {\n const doc = this._getDocument();\n return doc.defaultView || window;\n }\n _getFocusOrigin(focusEventTarget) {\n if (this._origin) {\n // If the origin was realized via a touch interaction, we need to perform additional checks\n // to determine whether the focus origin should be attributed to touch or program.\n if (this._originFromTouchInteraction) {\n return this._shouldBeAttributedToTouch(focusEventTarget) ? 'touch' : 'program';\n } else {\n return this._origin;\n }\n }\n // If the window has just regained focus, we can restore the most recent origin from before the\n // window blurred. Otherwise, we've reached the point where we can't identify the source of the\n // focus. This typically means one of two things happened:\n //\n // 1) The element was programmatically focused, or\n // 2) The element was focused via screen reader navigation (which generally doesn't fire\n // events).\n //\n // Because we can't distinguish between these two cases, we default to setting `program`.\n if (this._windowFocused && this._lastFocusOrigin) {\n return this._lastFocusOrigin;\n }\n // If the interaction is coming from an input label, we consider it a mouse interactions.\n // This is a special case where focus moves on `click`, rather than `mousedown` which breaks\n // our detection, because all our assumptions are for `mousedown`. We need to handle this\n // special case, because it's very common for checkboxes and radio buttons.\n if (focusEventTarget && this._isLastInteractionFromInputLabel(focusEventTarget)) {\n return 'mouse';\n }\n return 'program';\n }\n /**\n * Returns whether the focus event should be attributed to touch. Recall that in IMMEDIATE mode, a\n * touch origin isn't immediately reset at the next tick (see _setOrigin). This means that when we\n * handle a focus event following a touch interaction, we need to determine whether (1) the focus\n * event was directly caused by the touch interaction or (2) the focus event was caused by a\n * subsequent programmatic focus call triggered by the touch interaction.\n * @param focusEventTarget The target of the focus event under examination.\n */\n _shouldBeAttributedToTouch(focusEventTarget) {\n // Please note that this check is not perfect. Consider the following edge case:\n //\n // \n //\n // Suppose there is a FocusMonitor in IMMEDIATE mode attached to #parent. When the user touches\n // #child, #parent is programmatically focused. This code will attribute the focus to touch\n // instead of program. This is a relatively minor edge-case that can be worked around by using\n // focusVia(parent, 'program') to focus #parent.\n return this._detectionMode === FocusMonitorDetectionMode.EVENTUAL || !!focusEventTarget?.contains(this._inputModalityDetector._mostRecentTarget);\n }\n /**\n * Sets the focus classes on the element based on the given focus origin.\n * @param element The element to update the classes on.\n * @param origin The focus origin.\n */\n _setClasses(element, origin) {\n element.classList.toggle('cdk-focused', !!origin);\n element.classList.toggle('cdk-touch-focused', origin === 'touch');\n element.classList.toggle('cdk-keyboard-focused', origin === 'keyboard');\n element.classList.toggle('cdk-mouse-focused', origin === 'mouse');\n element.classList.toggle('cdk-program-focused', origin === 'program');\n }\n /**\n * Updates the focus origin. If we're using immediate detection mode, we schedule an async\n * function to clear the origin at the end of a timeout. The duration of the timeout depends on\n * the origin being set.\n * @param origin The origin to set.\n * @param isFromInteraction Whether we are setting the origin from an interaction event.\n */\n _setOrigin(origin, isFromInteraction = false) {\n this._ngZone.runOutsideAngular(() => {\n this._origin = origin;\n this._originFromTouchInteraction = origin === 'touch' && isFromInteraction;\n // If we're in IMMEDIATE mode, reset the origin at the next tick (or in `TOUCH_BUFFER_MS` ms\n // for a touch event). We reset the origin at the next tick because Firefox focuses one tick\n // after the interaction event. We wait `TOUCH_BUFFER_MS` ms before resetting the origin for\n // a touch event because when a touch event is fired, the associated focus event isn't yet in\n // the event queue. Before doing so, clear any pending timeouts.\n if (this._detectionMode === FocusMonitorDetectionMode.IMMEDIATE) {\n clearTimeout(this._originTimeoutId);\n const ms = this._originFromTouchInteraction ? TOUCH_BUFFER_MS : 1;\n this._originTimeoutId = setTimeout(() => this._origin = null, ms);\n }\n });\n }\n /**\n * Handles focus events on a registered element.\n * @param event The focus event.\n * @param element The monitored element.\n */\n _onFocus(event, element) {\n // NOTE(mmalerba): We currently set the classes based on the focus origin of the most recent\n // focus event affecting the monitored element. If we want to use the origin of the first event\n // instead we should check for the cdk-focused class here and return if the element already has\n // it. (This only matters for elements that have includesChildren = true).\n // If we are not counting child-element-focus as focused, make sure that the event target is the\n // monitored element itself.\n const elementInfo = this._elementInfo.get(element);\n const focusEventTarget = _getEventTarget(event);\n if (!elementInfo || !elementInfo.checkChildren && element !== focusEventTarget) {\n return;\n }\n this._originChanged(element, this._getFocusOrigin(focusEventTarget), elementInfo);\n }\n /**\n * Handles blur events on a registered element.\n * @param event The blur event.\n * @param element The monitored element.\n */\n _onBlur(event, element) {\n // If we are counting child-element-focus as focused, make sure that we aren't just blurring in\n // order to focus another child of the monitored element.\n const elementInfo = this._elementInfo.get(element);\n if (!elementInfo || elementInfo.checkChildren && event.relatedTarget instanceof Node && element.contains(event.relatedTarget)) {\n return;\n }\n this._setClasses(element);\n this._emitOrigin(elementInfo, null);\n }\n _emitOrigin(info, origin) {\n if (info.subject.observers.length) {\n this._ngZone.run(() => info.subject.next(origin));\n }\n }\n _registerGlobalListeners(elementInfo) {\n if (!this._platform.isBrowser) {\n return;\n }\n const rootNode = elementInfo.rootNode;\n const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode) || 0;\n if (!rootNodeFocusListeners) {\n this._ngZone.runOutsideAngular(() => {\n rootNode.addEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);\n rootNode.addEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);\n });\n }\n this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners + 1);\n // Register global listeners when first element is monitored.\n if (++this._monitoredElementCount === 1) {\n // Note: we listen to events in the capture phase so we\n // can detect them even if the user stops propagation.\n this._ngZone.runOutsideAngular(() => {\n const window = this._getWindow();\n window.addEventListener('focus', this._windowFocusListener);\n });\n // The InputModalityDetector is also just a collection of global listeners.\n this._inputModalityDetector.modalityDetected.pipe(takeUntil(this._stopInputModalityDetector)).subscribe(modality => {\n this._setOrigin(modality, true /* isFromInteraction */);\n });\n }\n }\n _removeGlobalListeners(elementInfo) {\n const rootNode = elementInfo.rootNode;\n if (this._rootNodeFocusListenerCount.has(rootNode)) {\n const rootNodeFocusListeners = this._rootNodeFocusListenerCount.get(rootNode);\n if (rootNodeFocusListeners > 1) {\n this._rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners - 1);\n } else {\n rootNode.removeEventListener('focus', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);\n rootNode.removeEventListener('blur', this._rootNodeFocusAndBlurListener, captureEventListenerOptions);\n this._rootNodeFocusListenerCount.delete(rootNode);\n }\n }\n // Unregister global listeners when last element is unmonitored.\n if (! --this._monitoredElementCount) {\n const window = this._getWindow();\n window.removeEventListener('focus', this._windowFocusListener);\n // Equivalently, stop our InputModalityDetector subscription.\n this._stopInputModalityDetector.next();\n // Clear timeouts for all potentially pending timeouts to prevent the leaks.\n clearTimeout(this._windowFocusTimeoutId);\n clearTimeout(this._originTimeoutId);\n }\n }\n /** Updates all the state on an element once its focus origin has changed. */\n _originChanged(element, origin, elementInfo) {\n this._setClasses(element, origin);\n this._emitOrigin(elementInfo, origin);\n this._lastFocusOrigin = origin;\n }\n /**\n * Collects the `MonitoredElementInfo` of a particular element and\n * all of its ancestors that have enabled `checkChildren`.\n * @param element Element from which to start the search.\n */\n _getClosestElementsInfo(element) {\n const results = [];\n this._elementInfo.forEach((info, currentElement) => {\n if (currentElement === element || info.checkChildren && currentElement.contains(element)) {\n results.push([currentElement, info]);\n }\n });\n return results;\n }\n /**\n * Returns whether an interaction is likely to have come from the user clicking the `label` of\n * an `input` or `textarea` in order to focus it.\n * @param focusEventTarget Target currently receiving focus.\n */\n _isLastInteractionFromInputLabel(focusEventTarget) {\n const {\n _mostRecentTarget: mostRecentTarget,\n mostRecentModality\n } = this._inputModalityDetector;\n // If the last interaction used the mouse on an element contained by one of the labels\n // of an `input`/`textarea` that is currently focused, it is very likely that the\n // user redirected focus using the label.\n if (mostRecentModality !== 'mouse' || !mostRecentTarget || mostRecentTarget === focusEventTarget || focusEventTarget.nodeName !== 'INPUT' && focusEventTarget.nodeName !== 'TEXTAREA' || focusEventTarget.disabled) {\n return false;\n }\n const labels = focusEventTarget.labels;\n if (labels) {\n for (let i = 0; i < labels.length; i++) {\n if (labels[i].contains(mostRecentTarget)) {\n return true;\n }\n }\n }\n return false;\n }\n static ɵfac = function FocusMonitor_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || FocusMonitor)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: FocusMonitor,\n factory: FocusMonitor.ɵfac,\n providedIn: 'root'\n });\n }\n return FocusMonitor;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Directive that determines how a particular element was focused (via keyboard, mouse, touch, or\n * programmatically) and adds corresponding classes to the element.\n *\n * There are two variants of this directive:\n * 1) cdkMonitorElementFocus: does not consider an element to be focused if one of its children is\n * focused.\n * 2) cdkMonitorSubtreeFocus: considers an element focused if it or any of its children are focused.\n */\nlet CdkMonitorFocus = /*#__PURE__*/(() => {\n class CdkMonitorFocus {\n _elementRef = inject(ElementRef);\n _focusMonitor = inject(FocusMonitor);\n _monitorSubscription;\n _focusOrigin = null;\n cdkFocusChange = new EventEmitter();\n constructor() {}\n get focusOrigin() {\n return this._focusOrigin;\n }\n ngAfterViewInit() {\n const element = this._elementRef.nativeElement;\n this._monitorSubscription = this._focusMonitor.monitor(element, element.nodeType === 1 && element.hasAttribute('cdkMonitorSubtreeFocus')).subscribe(origin => {\n this._focusOrigin = origin;\n this.cdkFocusChange.emit(origin);\n });\n }\n ngOnDestroy() {\n this._focusMonitor.stopMonitoring(this._elementRef);\n if (this._monitorSubscription) {\n this._monitorSubscription.unsubscribe();\n }\n }\n static ɵfac = function CdkMonitorFocus_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || CdkMonitorFocus)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: CdkMonitorFocus,\n selectors: [[\"\", \"cdkMonitorElementFocus\", \"\"], [\"\", \"cdkMonitorSubtreeFocus\", \"\"]],\n outputs: {\n cdkFocusChange: \"cdkFocusChange\"\n },\n exportAs: [\"cdkMonitorFocus\"]\n });\n }\n return CdkMonitorFocus;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Set of possible high-contrast mode backgrounds. */\nvar HighContrastMode = /*#__PURE__*/function (HighContrastMode) {\n HighContrastMode[HighContrastMode[\"NONE\"] = 0] = \"NONE\";\n HighContrastMode[HighContrastMode[\"BLACK_ON_WHITE\"] = 1] = \"BLACK_ON_WHITE\";\n HighContrastMode[HighContrastMode[\"WHITE_ON_BLACK\"] = 2] = \"WHITE_ON_BLACK\";\n return HighContrastMode;\n}(HighContrastMode || {});\n/** CSS class applied to the document body when in black-on-white high-contrast mode. */\nconst BLACK_ON_WHITE_CSS_CLASS = 'cdk-high-contrast-black-on-white';\n/** CSS class applied to the document body when in white-on-black high-contrast mode. */\nconst WHITE_ON_BLACK_CSS_CLASS = 'cdk-high-contrast-white-on-black';\n/** CSS class applied to the document body when in high-contrast mode. */\nconst HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS = 'cdk-high-contrast-active';\n/**\n * Service to determine whether the browser is currently in a high-contrast-mode environment.\n *\n * Microsoft Windows supports an accessibility feature called \"High Contrast Mode\". This mode\n * changes the appearance of all applications, including web applications, to dramatically increase\n * contrast.\n *\n * IE, Edge, and Firefox currently support this mode. Chrome does not support Windows High Contrast\n * Mode. This service does not detect high-contrast mode as added by the Chrome \"High Contrast\"\n * browser extension.\n */\nlet HighContrastModeDetector = /*#__PURE__*/(() => {\n class HighContrastModeDetector {\n _platform = inject(Platform);\n /**\n * Figuring out the high contrast mode and adding the body classes can cause\n * some expensive layouts. This flag is used to ensure that we only do it once.\n */\n _hasCheckedHighContrastMode;\n _document = inject(DOCUMENT);\n _breakpointSubscription;\n constructor() {\n this._breakpointSubscription = inject(BreakpointObserver).observe('(forced-colors: active)').subscribe(() => {\n if (this._hasCheckedHighContrastMode) {\n this._hasCheckedHighContrastMode = false;\n this._applyBodyHighContrastModeCssClasses();\n }\n });\n }\n /** Gets the current high-contrast-mode for the page. */\n getHighContrastMode() {\n if (!this._platform.isBrowser) {\n return HighContrastMode.NONE;\n }\n // Create a test element with an arbitrary background-color that is neither black nor\n // white; high-contrast mode will coerce the color to either black or white. Also ensure that\n // appending the test element to the DOM does not affect layout by absolutely positioning it\n const testElement = this._document.createElement('div');\n testElement.style.backgroundColor = 'rgb(1,2,3)';\n testElement.style.position = 'absolute';\n this._document.body.appendChild(testElement);\n // Get the computed style for the background color, collapsing spaces to normalize between\n // browsers. Once we get this color, we no longer need the test element. Access the `window`\n // via the document so we can fake it in tests. Note that we have extra null checks, because\n // this logic will likely run during app bootstrap and throwing can break the entire app.\n const documentWindow = this._document.defaultView || window;\n const computedStyle = documentWindow && documentWindow.getComputedStyle ? documentWindow.getComputedStyle(testElement) : null;\n const computedColor = (computedStyle && computedStyle.backgroundColor || '').replace(/ /g, '');\n testElement.remove();\n switch (computedColor) {\n // Pre Windows 11 dark theme.\n case 'rgb(0,0,0)':\n // Windows 11 dark themes.\n case 'rgb(45,50,54)':\n case 'rgb(32,32,32)':\n return HighContrastMode.WHITE_ON_BLACK;\n // Pre Windows 11 light theme.\n case 'rgb(255,255,255)':\n // Windows 11 light theme.\n case 'rgb(255,250,239)':\n return HighContrastMode.BLACK_ON_WHITE;\n }\n return HighContrastMode.NONE;\n }\n ngOnDestroy() {\n this._breakpointSubscription.unsubscribe();\n }\n /** Applies CSS classes indicating high-contrast mode to document body (browser-only). */\n _applyBodyHighContrastModeCssClasses() {\n if (!this._hasCheckedHighContrastMode && this._platform.isBrowser && this._document.body) {\n const bodyClasses = this._document.body.classList;\n bodyClasses.remove(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS, BLACK_ON_WHITE_CSS_CLASS, WHITE_ON_BLACK_CSS_CLASS);\n this._hasCheckedHighContrastMode = true;\n const mode = this.getHighContrastMode();\n if (mode === HighContrastMode.BLACK_ON_WHITE) {\n bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS, BLACK_ON_WHITE_CSS_CLASS);\n } else if (mode === HighContrastMode.WHITE_ON_BLACK) {\n bodyClasses.add(HIGH_CONTRAST_MODE_ACTIVE_CSS_CLASS, WHITE_ON_BLACK_CSS_CLASS);\n }\n }\n }\n static ɵfac = function HighContrastModeDetector_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || HighContrastModeDetector)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: HighContrastModeDetector,\n factory: HighContrastModeDetector.ɵfac,\n providedIn: 'root'\n });\n }\n return HighContrastModeDetector;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet A11yModule = /*#__PURE__*/(() => {\n class A11yModule {\n constructor() {\n inject(HighContrastModeDetector)._applyBodyHighContrastModeCssClasses();\n }\n static ɵfac = function A11yModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || A11yModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: A11yModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n imports: [ObserversModule]\n });\n }\n return A11yModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Keeps track of the ID count per prefix. This helps us make the IDs a bit more deterministic\n * like they were before the service was introduced. Note that ideally we wouldn't have to do\n * this, but there are some internal tests that rely on the IDs.\n */\nconst counters = {};\n/** Service that generates unique IDs for DOM nodes. */\nlet _IdGenerator = /*#__PURE__*/(() => {\n class _IdGenerator {\n _appId = inject(APP_ID);\n /**\n * Generates a unique ID with a specific prefix.\n * @param prefix Prefix to add to the ID.\n */\n getId(prefix) {\n // Omit the app ID if it's the default `ng`. Since the vast majority of pages have one\n // Angular app on them, we can reduce the amount of breakages by not adding it.\n if (this._appId !== 'ng') {\n prefix += this._appId;\n }\n if (!counters.hasOwnProperty(prefix)) {\n counters[prefix] = 0;\n }\n return `${prefix}${counters[prefix]++}`;\n }\n static ɵfac = function _IdGenerator_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || _IdGenerator)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: _IdGenerator,\n factory: _IdGenerator.ɵfac,\n providedIn: 'root'\n });\n }\n return _IdGenerator;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { A11yModule, ActiveDescendantKeyManager, AriaDescriber, CDK_DESCRIBEDBY_HOST_ATTRIBUTE, CDK_DESCRIBEDBY_ID_PREFIX, CdkAriaLive, CdkMonitorFocus, CdkTrapFocus, ConfigurableFocusTrap, ConfigurableFocusTrapFactory, EventListenerFocusTrapInertStrategy, FOCUS_MONITOR_DEFAULT_OPTIONS, FOCUS_TRAP_INERT_STRATEGY, FocusKeyManager, FocusMonitor, FocusMonitorDetectionMode, FocusTrap, FocusTrapFactory, HighContrastMode, HighContrastModeDetector, INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS, INPUT_MODALITY_DETECTOR_OPTIONS, InputModalityDetector, InteractivityChecker, IsFocusableConfig, LIVE_ANNOUNCER_DEFAULT_OPTIONS, LIVE_ANNOUNCER_ELEMENT_TOKEN, LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY, ListKeyManager, LiveAnnouncer, MESSAGES_CONTAINER_ID, NOOP_TREE_KEY_MANAGER_FACTORY, NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER, NoopTreeKeyManager, TREE_KEY_MANAGER, TREE_KEY_MANAGER_FACTORY, TREE_KEY_MANAGER_FACTORY_PROVIDER, TreeKeyManager, _IdGenerator, addAriaReferencedId, getAriaReferenceIds, isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader, removeAriaReferencedId };\n","import * as i0 from '@angular/core';\nimport { Version, InjectionToken, inject, NgModule, LOCALE_ID, Injectable, Component, ViewEncapsulation, ChangeDetectionStrategy, Directive, ElementRef, ANIMATION_MODULE_TYPE, NgZone, Injector, Input, booleanAttribute, ChangeDetectorRef, EventEmitter, isSignal, Output, ViewChild } from '@angular/core';\nimport { HighContrastModeDetector, isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader, _IdGenerator } from '@angular/cdk/a11y';\nimport { BidiModule } from '@angular/cdk/bidi';\nimport { Subject } from 'rxjs';\nimport { startWith } from 'rxjs/operators';\nimport { normalizePassiveListenerOptions, _getEventTarget, Platform } from '@angular/cdk/platform';\nimport { coerceElement } from '@angular/cdk/coercion';\nimport { _CdkPrivateStyleLoader, _VisuallyHiddenLoader } from '@angular/cdk/private';\nimport { ENTER, SPACE, hasModifierKey } from '@angular/cdk/keycodes';\nimport { DOCUMENT } from '@angular/common';\n\n/** Current version of Angular Material. */\nconst _c0 = [\"*\", [[\"mat-option\"], [\"ng-container\"]]];\nconst _c1 = [\"*\", \"mat-option, ng-container\"];\nconst _c2 = [\"text\"];\nconst _c3 = [[[\"mat-icon\"]], \"*\"];\nconst _c4 = [\"mat-icon\", \"*\"];\nfunction MatOption_Conditional_0_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"mat-pseudo-checkbox\", 1);\n }\n if (rf & 2) {\n const ctx_r0 = i0.ɵɵnextContext();\n i0.ɵɵproperty(\"disabled\", ctx_r0.disabled)(\"state\", ctx_r0.selected ? \"checked\" : \"unchecked\");\n }\n}\nfunction MatOption_Conditional_5_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"mat-pseudo-checkbox\", 3);\n }\n if (rf & 2) {\n const ctx_r0 = i0.ɵɵnextContext();\n i0.ɵɵproperty(\"disabled\", ctx_r0.disabled);\n }\n}\nfunction MatOption_Conditional_6_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"span\", 4);\n i0.ɵɵtext(1);\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const ctx_r0 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate1(\"(\", ctx_r0.group.label, \")\");\n }\n}\nconst _c5 = [\"mat-internal-form-field\", \"\"];\nconst _c6 = [\"*\"];\nconst VERSION = /*#__PURE__*/new Version('19.0.3');\n\n/** @docs-private */\nlet AnimationCurves = /*#__PURE__*/(() => {\n class AnimationCurves {\n static STANDARD_CURVE = 'cubic-bezier(0.4,0.0,0.2,1)';\n static DECELERATION_CURVE = 'cubic-bezier(0.0,0.0,0.2,1)';\n static ACCELERATION_CURVE = 'cubic-bezier(0.4,0.0,1,1)';\n static SHARP_CURVE = 'cubic-bezier(0.4,0.0,0.6,1)';\n }\n return AnimationCurves;\n})();\n/** @docs-private */\nlet AnimationDurations = /*#__PURE__*/(() => {\n class AnimationDurations {\n static COMPLEX = '375ms';\n static ENTERING = '225ms';\n static EXITING = '195ms';\n }\n return AnimationDurations;\n})();\n/**\n * Injection token that configures whether the Material sanity checks are enabled.\n * @deprecated No longer used and will be removed.\n * @breaking-change 21.0.0\n */\nconst MATERIAL_SANITY_CHECKS = /*#__PURE__*/new InjectionToken('mat-sanity-checks', {\n providedIn: 'root',\n factory: () => true\n});\n/**\n * Module that captures anything that should be loaded and/or run for *all* Angular Material\n * components. This includes Bidi, etc.\n *\n * This module should be imported to each top-level component module (e.g., MatTabsModule).\n * @deprecated No longer used and will be removed.\n * @breaking-change 21.0.0\n */\nlet MatCommonModule = /*#__PURE__*/(() => {\n class MatCommonModule {\n constructor() {\n // While A11yModule also does this, we repeat it here to avoid importing A11yModule\n // in MatCommonModule.\n inject(HighContrastModeDetector)._applyBodyHighContrastModeCssClasses();\n }\n static ɵfac = function MatCommonModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || MatCommonModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: MatCommonModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n imports: [BidiModule, BidiModule]\n });\n }\n return MatCommonModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Class that tracks the error state of a component.\n * @docs-private\n */\nclass _ErrorStateTracker {\n _defaultMatcher;\n ngControl;\n _parentFormGroup;\n _parentForm;\n _stateChanges;\n /** Whether the tracker is currently in an error state. */\n errorState = false;\n /** User-defined matcher for the error state. */\n matcher;\n constructor(_defaultMatcher, ngControl, _parentFormGroup, _parentForm, _stateChanges) {\n this._defaultMatcher = _defaultMatcher;\n this.ngControl = ngControl;\n this._parentFormGroup = _parentFormGroup;\n this._parentForm = _parentForm;\n this._stateChanges = _stateChanges;\n }\n /** Updates the error state based on the provided error state matcher. */\n updateErrorState() {\n const oldState = this.errorState;\n const parent = this._parentFormGroup || this._parentForm;\n const matcher = this.matcher || this._defaultMatcher;\n const control = this.ngControl ? this.ngControl.control : null;\n const newState = matcher?.isErrorState(control, parent) ?? false;\n if (newState !== oldState) {\n this.errorState = newState;\n this._stateChanges.next();\n }\n }\n}\n\n/** InjectionToken for datepicker that can be used to override default locale code. */\nconst MAT_DATE_LOCALE = /*#__PURE__*/new InjectionToken('MAT_DATE_LOCALE', {\n providedIn: 'root',\n factory: MAT_DATE_LOCALE_FACTORY\n});\n/** @docs-private */\nfunction MAT_DATE_LOCALE_FACTORY() {\n return inject(LOCALE_ID);\n}\nconst NOT_IMPLEMENTED = 'Method not implemented';\n/** Adapts type `D` to be usable as a date by cdk-based components that work with dates. */\nclass DateAdapter {\n /** The locale to use for all dates. */\n locale;\n _localeChanges = /*#__PURE__*/new Subject();\n /** A stream that emits when the locale changes. */\n localeChanges = this._localeChanges;\n /**\n * Sets the time of one date to the time of another.\n * @param target Date whose time will be set.\n * @param hours New hours to set on the date object.\n * @param minutes New minutes to set on the date object.\n * @param seconds New seconds to set on the date object.\n */\n setTime(target, hours, minutes, seconds) {\n throw new Error(NOT_IMPLEMENTED);\n }\n /**\n * Gets the hours component of the given date.\n * @param date The date to extract the hours from.\n */\n getHours(date) {\n throw new Error(NOT_IMPLEMENTED);\n }\n /**\n * Gets the minutes component of the given date.\n * @param date The date to extract the minutes from.\n */\n getMinutes(date) {\n throw new Error(NOT_IMPLEMENTED);\n }\n /**\n * Gets the seconds component of the given date.\n * @param date The date to extract the seconds from.\n */\n getSeconds(date) {\n throw new Error(NOT_IMPLEMENTED);\n }\n /**\n * Parses a date with a specific time from a user-provided value.\n * @param value The value to parse.\n * @param parseFormat The expected format of the value being parsed\n * (type is implementation-dependent).\n */\n parseTime(value, parseFormat) {\n throw new Error(NOT_IMPLEMENTED);\n }\n /**\n * Adds an amount of seconds to the specified date.\n * @param date Date to which to add the seconds.\n * @param amount Amount of seconds to add to the date.\n */\n addSeconds(date, amount) {\n throw new Error(NOT_IMPLEMENTED);\n }\n /**\n * Given a potential date object, returns that same date object if it is\n * a valid date, or `null` if it's not a valid date.\n * @param obj The object to check.\n * @returns A date or `null`.\n */\n getValidDateOrNull(obj) {\n return this.isDateInstance(obj) && this.isValid(obj) ? obj : null;\n }\n /**\n * Attempts to deserialize a value to a valid date object. This is different from parsing in that\n * deserialize should only accept non-ambiguous, locale-independent formats (e.g. a ISO 8601\n * string). The default implementation does not allow any deserialization, it simply checks that\n * the given value is already a valid date object or null. The `` will call this\n * method on all of its `@Input()` properties that accept dates. It is therefore possible to\n * support passing values from your backend directly to these properties by overriding this method\n * to also deserialize the format used by your backend.\n * @param value The value to be deserialized into a date object.\n * @returns The deserialized date object, either a valid date, null if the value can be\n * deserialized into a null date (e.g. the empty string), or an invalid date.\n */\n deserialize(value) {\n if (value == null || this.isDateInstance(value) && this.isValid(value)) {\n return value;\n }\n return this.invalid();\n }\n /**\n * Sets the locale used for all dates.\n * @param locale The new locale.\n */\n setLocale(locale) {\n this.locale = locale;\n this._localeChanges.next();\n }\n /**\n * Compares two dates.\n * @param first The first date to compare.\n * @param second The second date to compare.\n * @returns 0 if the dates are equal, a number less than 0 if the first date is earlier,\n * a number greater than 0 if the first date is later.\n */\n compareDate(first, second) {\n return this.getYear(first) - this.getYear(second) || this.getMonth(first) - this.getMonth(second) || this.getDate(first) - this.getDate(second);\n }\n /**\n * Compares the time values of two dates.\n * @param first First date to compare.\n * @param second Second date to compare.\n * @returns 0 if the times are equal, a number less than 0 if the first time is earlier,\n * a number greater than 0 if the first time is later.\n */\n compareTime(first, second) {\n return this.getHours(first) - this.getHours(second) || this.getMinutes(first) - this.getMinutes(second) || this.getSeconds(first) - this.getSeconds(second);\n }\n /**\n * Checks if two dates are equal.\n * @param first The first date to check.\n * @param second The second date to check.\n * @returns Whether the two dates are equal.\n * Null dates are considered equal to other null dates.\n */\n sameDate(first, second) {\n if (first && second) {\n let firstValid = this.isValid(first);\n let secondValid = this.isValid(second);\n if (firstValid && secondValid) {\n return !this.compareDate(first, second);\n }\n return firstValid == secondValid;\n }\n return first == second;\n }\n /**\n * Checks if the times of two dates are equal.\n * @param first The first date to check.\n * @param second The second date to check.\n * @returns Whether the times of the two dates are equal.\n * Null dates are considered equal to other null dates.\n */\n sameTime(first, second) {\n if (first && second) {\n const firstValid = this.isValid(first);\n const secondValid = this.isValid(second);\n if (firstValid && secondValid) {\n return !this.compareTime(first, second);\n }\n return firstValid == secondValid;\n }\n return first == second;\n }\n /**\n * Clamp the given date between min and max dates.\n * @param date The date to clamp.\n * @param min The minimum value to allow. If null or omitted no min is enforced.\n * @param max The maximum value to allow. If null or omitted no max is enforced.\n * @returns `min` if `date` is less than `min`, `max` if date is greater than `max`,\n * otherwise `date`.\n */\n clampDate(date, min, max) {\n if (min && this.compareDate(date, min) < 0) {\n return min;\n }\n if (max && this.compareDate(date, max) > 0) {\n return max;\n }\n return date;\n }\n}\nconst MAT_DATE_FORMATS = /*#__PURE__*/new InjectionToken('mat-date-formats');\n\n/**\n * Matches strings that have the form of a valid RFC 3339 string\n * (https://tools.ietf.org/html/rfc3339). Note that the string may not actually be a valid date\n * because the regex will match strings with an out of bounds month, date, etc.\n */\nconst ISO_8601_REGEX = /^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|(?:(?:\\+|-)\\d{2}:\\d{2}))?)?$/;\n/**\n * Matches a time string. Supported formats:\n * - {{hours}}:{{minutes}}\n * - {{hours}}:{{minutes}}:{{seconds}}\n * - {{hours}}:{{minutes}} AM/PM\n * - {{hours}}:{{minutes}}:{{seconds}} AM/PM\n * - {{hours}}.{{minutes}}\n * - {{hours}}.{{minutes}}.{{seconds}}\n * - {{hours}}.{{minutes}} AM/PM\n * - {{hours}}.{{minutes}}.{{seconds}} AM/PM\n */\nconst TIME_REGEX = /^(\\d?\\d)[:.](\\d?\\d)(?:[:.](\\d?\\d))?\\s*(AM|PM)?$/i;\n/** Creates an array and fills it with values. */\nfunction range(length, valueFunction) {\n const valuesArray = Array(length);\n for (let i = 0; i < length; i++) {\n valuesArray[i] = valueFunction(i);\n }\n return valuesArray;\n}\n/** Adapts the native JS Date for use with cdk-based components that work with dates. */\nlet NativeDateAdapter = /*#__PURE__*/(() => {\n class NativeDateAdapter extends DateAdapter {\n /**\n * @deprecated No longer being used. To be removed.\n * @breaking-change 14.0.0\n */\n useUtcForDisplay = false;\n /** The injected locale. */\n _matDateLocale = inject(MAT_DATE_LOCALE, {\n optional: true\n });\n constructor() {\n super();\n const matDateLocale = inject(MAT_DATE_LOCALE, {\n optional: true\n });\n if (matDateLocale !== undefined) {\n this._matDateLocale = matDateLocale;\n }\n super.setLocale(this._matDateLocale);\n }\n getYear(date) {\n return date.getFullYear();\n }\n getMonth(date) {\n return date.getMonth();\n }\n getDate(date) {\n return date.getDate();\n }\n getDayOfWeek(date) {\n return date.getDay();\n }\n getMonthNames(style) {\n const dtf = new Intl.DateTimeFormat(this.locale, {\n month: style,\n timeZone: 'utc'\n });\n return range(12, i => this._format(dtf, new Date(2017, i, 1)));\n }\n getDateNames() {\n const dtf = new Intl.DateTimeFormat(this.locale, {\n day: 'numeric',\n timeZone: 'utc'\n });\n return range(31, i => this._format(dtf, new Date(2017, 0, i + 1)));\n }\n getDayOfWeekNames(style) {\n const dtf = new Intl.DateTimeFormat(this.locale, {\n weekday: style,\n timeZone: 'utc'\n });\n return range(7, i => this._format(dtf, new Date(2017, 0, i + 1)));\n }\n getYearName(date) {\n const dtf = new Intl.DateTimeFormat(this.locale, {\n year: 'numeric',\n timeZone: 'utc'\n });\n return this._format(dtf, date);\n }\n getFirstDayOfWeek() {\n // At the time of writing `Intl.Locale` isn't available\n // in the internal types so we need to cast to `any`.\n if (typeof Intl !== 'undefined' && Intl.Locale) {\n const locale = new Intl.Locale(this.locale);\n // Some browsers implement a `getWeekInfo` method while others have a `weekInfo` getter.\n // Note that this isn't supported in all browsers so we need to null check it.\n const firstDay = (locale.getWeekInfo?.() || locale.weekInfo)?.firstDay ?? 0;\n // `weekInfo.firstDay` is a number between 1 and 7 where, starting from Monday,\n // whereas our representation is 0 to 6 where 0 is Sunday so we need to normalize it.\n return firstDay === 7 ? 0 : firstDay;\n }\n // Default to Sunday if the browser doesn't provide the week information.\n return 0;\n }\n getNumDaysInMonth(date) {\n return this.getDate(this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + 1, 0));\n }\n clone(date) {\n return new Date(date.getTime());\n }\n createDate(year, month, date) {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n // Check for invalid month and date (except upper bound on date which we have to check after\n // creating the Date).\n if (month < 0 || month > 11) {\n throw Error(`Invalid month index \"${month}\". Month index has to be between 0 and 11.`);\n }\n if (date < 1) {\n throw Error(`Invalid date \"${date}\". Date has to be greater than 0.`);\n }\n }\n let result = this._createDateWithOverflow(year, month, date);\n // Check that the date wasn't above the upper bound for the month, causing the month to overflow\n if (result.getMonth() != month && (typeof ngDevMode === 'undefined' || ngDevMode)) {\n throw Error(`Invalid date \"${date}\" for month with index \"${month}\".`);\n }\n return result;\n }\n today() {\n return new Date();\n }\n parse(value, parseFormat) {\n // We have no way using the native JS Date to set the parse format or locale, so we ignore these\n // parameters.\n if (typeof value == 'number') {\n return new Date(value);\n }\n return value ? new Date(Date.parse(value)) : null;\n }\n format(date, displayFormat) {\n if (!this.isValid(date)) {\n throw Error('NativeDateAdapter: Cannot format invalid date.');\n }\n const dtf = new Intl.DateTimeFormat(this.locale, {\n ...displayFormat,\n timeZone: 'utc'\n });\n return this._format(dtf, date);\n }\n addCalendarYears(date, years) {\n return this.addCalendarMonths(date, years * 12);\n }\n addCalendarMonths(date, months) {\n let newDate = this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + months, this.getDate(date));\n // It's possible to wind up in the wrong month if the original month has more days than the new\n // month. In this case we want to go to the last day of the desired month.\n // Note: the additional + 12 % 12 ensures we end up with a positive number, since JS % doesn't\n // guarantee this.\n if (this.getMonth(newDate) != ((this.getMonth(date) + months) % 12 + 12) % 12) {\n newDate = this._createDateWithOverflow(this.getYear(newDate), this.getMonth(newDate), 0);\n }\n return newDate;\n }\n addCalendarDays(date, days) {\n return this._createDateWithOverflow(this.getYear(date), this.getMonth(date), this.getDate(date) + days);\n }\n toIso8601(date) {\n return [date.getUTCFullYear(), this._2digit(date.getUTCMonth() + 1), this._2digit(date.getUTCDate())].join('-');\n }\n /**\n * Returns the given value if given a valid Date or null. Deserializes valid ISO 8601 strings\n * (https://www.ietf.org/rfc/rfc3339.txt) into valid Dates and empty string into null. Returns an\n * invalid date for all other values.\n */\n deserialize(value) {\n if (typeof value === 'string') {\n if (!value) {\n return null;\n }\n // The `Date` constructor accepts formats other than ISO 8601, so we need to make sure the\n // string is the right format first.\n if (ISO_8601_REGEX.test(value)) {\n let date = new Date(value);\n if (this.isValid(date)) {\n return date;\n }\n }\n }\n return super.deserialize(value);\n }\n isDateInstance(obj) {\n return obj instanceof Date;\n }\n isValid(date) {\n return !isNaN(date.getTime());\n }\n invalid() {\n return new Date(NaN);\n }\n setTime(target, hours, minutes, seconds) {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (!inRange(hours, 0, 23)) {\n throw Error(`Invalid hours \"${hours}\". Hours value must be between 0 and 23.`);\n }\n if (!inRange(minutes, 0, 59)) {\n throw Error(`Invalid minutes \"${minutes}\". Minutes value must be between 0 and 59.`);\n }\n if (!inRange(seconds, 0, 59)) {\n throw Error(`Invalid seconds \"${seconds}\". Seconds value must be between 0 and 59.`);\n }\n }\n const clone = this.clone(target);\n clone.setHours(hours, minutes, seconds, 0);\n return clone;\n }\n getHours(date) {\n return date.getHours();\n }\n getMinutes(date) {\n return date.getMinutes();\n }\n getSeconds(date) {\n return date.getSeconds();\n }\n parseTime(userValue, parseFormat) {\n if (typeof userValue !== 'string') {\n return userValue instanceof Date ? new Date(userValue.getTime()) : null;\n }\n const value = userValue.trim();\n if (value.length === 0) {\n return null;\n }\n // Attempt to parse the value directly.\n let result = this._parseTimeString(value);\n // Some locales add extra characters around the time, but are otherwise parseable\n // (e.g. `00:05 ч.` in bg-BG). Try replacing all non-number and non-colon characters.\n if (result === null) {\n const withoutExtras = value.replace(/[^0-9:(AM|PM)]/gi, '').trim();\n if (withoutExtras.length > 0) {\n result = this._parseTimeString(withoutExtras);\n }\n }\n return result || this.invalid();\n }\n addSeconds(date, amount) {\n return new Date(date.getTime() + amount * 1000);\n }\n /** Creates a date but allows the month and date to overflow. */\n _createDateWithOverflow(year, month, date) {\n // Passing the year to the constructor causes year numbers <100 to be converted to 19xx.\n // To work around this we use `setFullYear` and `setHours` instead.\n const d = new Date();\n d.setFullYear(year, month, date);\n d.setHours(0, 0, 0, 0);\n return d;\n }\n /**\n * Pads a number to make it two digits.\n * @param n The number to pad.\n * @returns The padded number.\n */\n _2digit(n) {\n return ('00' + n).slice(-2);\n }\n /**\n * When converting Date object to string, javascript built-in functions may return wrong\n * results because it applies its internal DST rules. The DST rules around the world change\n * very frequently, and the current valid rule is not always valid in previous years though.\n * We work around this problem building a new Date object which has its internal UTC\n * representation with the local date and time.\n * @param dtf Intl.DateTimeFormat object, containing the desired string format. It must have\n * timeZone set to 'utc' to work fine.\n * @param date Date from which we want to get the string representation according to dtf\n * @returns A Date object with its UTC representation based on the passed in date info\n */\n _format(dtf, date) {\n // Passing the year to the constructor causes year numbers <100 to be converted to 19xx.\n // To work around this we use `setUTCFullYear` and `setUTCHours` instead.\n const d = new Date();\n d.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());\n d.setUTCHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());\n return dtf.format(d);\n }\n /**\n * Attempts to parse a time string into a date object. Returns null if it cannot be parsed.\n * @param value Time string to parse.\n */\n _parseTimeString(value) {\n // Note: we can technically rely on the browser for the time parsing by generating\n // an ISO string and appending the string to the end of it. We don't do it, because\n // browsers aren't consistent in what they support. Some examples:\n // - Safari doesn't support AM/PM.\n // - Firefox produces a valid date object if the time string has overflows (e.g. 12:75) while\n // other browsers produce an invalid date.\n // - Safari doesn't allow padded numbers.\n const parsed = value.toUpperCase().match(TIME_REGEX);\n if (parsed) {\n let hours = parseInt(parsed[1]);\n const minutes = parseInt(parsed[2]);\n let seconds = parsed[3] == null ? undefined : parseInt(parsed[3]);\n const amPm = parsed[4];\n if (hours === 12) {\n hours = amPm === 'AM' ? 0 : hours;\n } else if (amPm === 'PM') {\n hours += 12;\n }\n if (inRange(hours, 0, 23) && inRange(minutes, 0, 59) && (seconds == null || inRange(seconds, 0, 59))) {\n return this.setTime(this.today(), hours, minutes, seconds || 0);\n }\n }\n return null;\n }\n static ɵfac = function NativeDateAdapter_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || NativeDateAdapter)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NativeDateAdapter,\n factory: NativeDateAdapter.ɵfac\n });\n }\n return NativeDateAdapter;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/** Checks whether a number is within a certain range. */\nfunction inRange(value, min, max) {\n return !isNaN(value) && value >= min && value <= max;\n}\nconst MAT_NATIVE_DATE_FORMATS = {\n parse: {\n dateInput: null,\n timeInput: null\n },\n display: {\n dateInput: {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric'\n },\n timeInput: {\n hour: 'numeric',\n minute: 'numeric'\n },\n monthYearLabel: {\n year: 'numeric',\n month: 'short'\n },\n dateA11yLabel: {\n year: 'numeric',\n month: 'long',\n day: 'numeric'\n },\n monthYearA11yLabel: {\n year: 'numeric',\n month: 'long'\n },\n timeOptionLabel: {\n hour: 'numeric',\n minute: 'numeric'\n }\n }\n};\nlet NativeDateModule = /*#__PURE__*/(() => {\n class NativeDateModule {\n static ɵfac = function NativeDateModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || NativeDateModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: NativeDateModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: [{\n provide: DateAdapter,\n useClass: NativeDateAdapter\n }]\n });\n }\n return NativeDateModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet MatNativeDateModule = /*#__PURE__*/(() => {\n class MatNativeDateModule {\n static ɵfac = function MatNativeDateModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || MatNativeDateModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: MatNativeDateModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: [provideNativeDateAdapter()]\n });\n }\n return MatNativeDateModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction provideNativeDateAdapter(formats = MAT_NATIVE_DATE_FORMATS) {\n return [{\n provide: DateAdapter,\n useClass: NativeDateAdapter\n }, {\n provide: MAT_DATE_FORMATS,\n useValue: formats\n }];\n}\n\n/** Error state matcher that matches when a control is invalid and dirty. */\nlet ShowOnDirtyErrorStateMatcher = /*#__PURE__*/(() => {\n class ShowOnDirtyErrorStateMatcher {\n isErrorState(control, form) {\n return !!(control && control.invalid && (control.dirty || form && form.submitted));\n }\n static ɵfac = function ShowOnDirtyErrorStateMatcher_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || ShowOnDirtyErrorStateMatcher)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: ShowOnDirtyErrorStateMatcher,\n factory: ShowOnDirtyErrorStateMatcher.ɵfac\n });\n }\n return ShowOnDirtyErrorStateMatcher;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/** Provider that defines how form controls behave with regards to displaying error messages. */\nlet ErrorStateMatcher = /*#__PURE__*/(() => {\n class ErrorStateMatcher {\n isErrorState(control, form) {\n return !!(control && control.invalid && (control.touched || form && form.submitted));\n }\n static ɵfac = function ErrorStateMatcher_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || ErrorStateMatcher)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: ErrorStateMatcher,\n factory: ErrorStateMatcher.ɵfac,\n providedIn: 'root'\n });\n }\n return ErrorStateMatcher;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Component used to load structural styles for focus indicators.\n * @docs-private\n */\nlet _StructuralStylesLoader = /*#__PURE__*/(() => {\n class _StructuralStylesLoader {\n static ɵfac = function _StructuralStylesLoader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || _StructuralStylesLoader)();\n };\n static ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: _StructuralStylesLoader,\n selectors: [[\"structural-styles\"]],\n decls: 0,\n vars: 0,\n template: function _StructuralStylesLoader_Template(rf, ctx) {},\n styles: [\".mat-focus-indicator{position:relative}.mat-focus-indicator::before{top:0;left:0;right:0;bottom:0;position:absolute;box-sizing:border-box;pointer-events:none;display:var(--mat-focus-indicator-display, none);border-width:var(--mat-focus-indicator-border-width, 3px);border-style:var(--mat-focus-indicator-border-style, solid);border-color:var(--mat-focus-indicator-border-color, transparent);border-radius:var(--mat-focus-indicator-border-radius, 4px)}.mat-focus-indicator:focus::before{content:\\\"\\\"}@media(forced-colors: active){html{--mat-focus-indicator-display: block}}\"],\n encapsulation: 2,\n changeDetection: 0\n });\n }\n return _StructuralStylesLoader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Shared directive to count lines inside a text area, such as a list item.\n * Line elements can be extracted with a @ContentChildren(MatLine) query, then\n * counted by checking the query list's length.\n */\nlet MatLine = /*#__PURE__*/(() => {\n class MatLine {\n static ɵfac = function MatLine_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || MatLine)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: MatLine,\n selectors: [[\"\", \"mat-line\", \"\"], [\"\", \"matLine\", \"\"]],\n hostAttrs: [1, \"mat-line\"]\n });\n }\n return MatLine;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Helper that takes a query list of lines and sets the correct class on the host.\n * @docs-private\n */\nfunction setLines(lines, element, prefix = 'mat') {\n // Note: doesn't need to unsubscribe, because `changes`\n // gets completed by Angular when the view is destroyed.\n lines.changes.pipe(startWith(lines)).subscribe(({\n length\n }) => {\n setClass(element, `${prefix}-2-line`, false);\n setClass(element, `${prefix}-3-line`, false);\n setClass(element, `${prefix}-multi-line`, false);\n if (length === 2 || length === 3) {\n setClass(element, `${prefix}-${length}-line`, true);\n } else if (length > 3) {\n setClass(element, `${prefix}-multi-line`, true);\n }\n });\n}\n/** Adds or removes a class from an element. */\nfunction setClass(element, className, isAdd) {\n element.nativeElement.classList.toggle(className, isAdd);\n}\nlet MatLineModule = /*#__PURE__*/(() => {\n class MatLineModule {\n static ɵfac = function MatLineModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || MatLineModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: MatLineModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n imports: [MatCommonModule, MatCommonModule]\n });\n }\n return MatLineModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/** Possible states for a ripple element. */\nvar RippleState = /*#__PURE__*/function (RippleState) {\n RippleState[RippleState[\"FADING_IN\"] = 0] = \"FADING_IN\";\n RippleState[RippleState[\"VISIBLE\"] = 1] = \"VISIBLE\";\n RippleState[RippleState[\"FADING_OUT\"] = 2] = \"FADING_OUT\";\n RippleState[RippleState[\"HIDDEN\"] = 3] = \"HIDDEN\";\n return RippleState;\n}(RippleState || {});\n/**\n * Reference to a previously launched ripple element.\n */\nclass RippleRef {\n _renderer;\n element;\n config;\n _animationForciblyDisabledThroughCss;\n /** Current state of the ripple. */\n state = RippleState.HIDDEN;\n constructor(_renderer, /** Reference to the ripple HTML element. */\n element, /** Ripple configuration used for the ripple. */\n config, /* Whether animations are forcibly disabled for ripples through CSS. */\n _animationForciblyDisabledThroughCss = false) {\n this._renderer = _renderer;\n this.element = element;\n this.config = config;\n this._animationForciblyDisabledThroughCss = _animationForciblyDisabledThroughCss;\n }\n /** Fades out the ripple element. */\n fadeOut() {\n this._renderer.fadeOutRipple(this);\n }\n}\n\n/** Options used to bind a passive capturing event. */\nconst passiveCapturingEventOptions$1 = /*#__PURE__*/normalizePassiveListenerOptions({\n passive: true,\n capture: true\n});\n/** Manages events through delegation so that as few event handlers as possible are bound. */\nclass RippleEventManager {\n _events = /*#__PURE__*/new Map();\n /** Adds an event handler. */\n addHandler(ngZone, name, element, handler) {\n const handlersForEvent = this._events.get(name);\n if (handlersForEvent) {\n const handlersForElement = handlersForEvent.get(element);\n if (handlersForElement) {\n handlersForElement.add(handler);\n } else {\n handlersForEvent.set(element, new Set([handler]));\n }\n } else {\n this._events.set(name, new Map([[element, new Set([handler])]]));\n ngZone.runOutsideAngular(() => {\n document.addEventListener(name, this._delegateEventHandler, passiveCapturingEventOptions$1);\n });\n }\n }\n /** Removes an event handler. */\n removeHandler(name, element, handler) {\n const handlersForEvent = this._events.get(name);\n if (!handlersForEvent) {\n return;\n }\n const handlersForElement = handlersForEvent.get(element);\n if (!handlersForElement) {\n return;\n }\n handlersForElement.delete(handler);\n if (handlersForElement.size === 0) {\n handlersForEvent.delete(element);\n }\n if (handlersForEvent.size === 0) {\n this._events.delete(name);\n document.removeEventListener(name, this._delegateEventHandler, passiveCapturingEventOptions$1);\n }\n }\n /** Event handler that is bound and which dispatches the events to the different targets. */\n _delegateEventHandler = event => {\n const target = _getEventTarget(event);\n if (target) {\n this._events.get(event.type)?.forEach((handlers, element) => {\n if (element === target || element.contains(target)) {\n handlers.forEach(handler => handler.handleEvent(event));\n }\n });\n }\n };\n}\n\n/**\n * Default ripple animation configuration for ripples without an explicit\n * animation config specified.\n */\nconst defaultRippleAnimationConfig = {\n enterDuration: 225,\n exitDuration: 150\n};\n/**\n * Timeout for ignoring mouse events. Mouse events will be temporary ignored after touch\n * events to avoid synthetic mouse events.\n */\nconst ignoreMouseEventsTimeout = 800;\n/** Options used to bind a passive capturing event. */\nconst passiveCapturingEventOptions = /*#__PURE__*/normalizePassiveListenerOptions({\n passive: true,\n capture: true\n});\n/** Events that signal that the pointer is down. */\nconst pointerDownEvents = ['mousedown', 'touchstart'];\n/** Events that signal that the pointer is up. */\nconst pointerUpEvents = ['mouseup', 'mouseleave', 'touchend', 'touchcancel'];\nlet _MatRippleStylesLoader = /*#__PURE__*/(() => {\n class _MatRippleStylesLoader {\n static ɵfac = function _MatRippleStylesLoader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || _MatRippleStylesLoader)();\n };\n static ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: _MatRippleStylesLoader,\n selectors: [[\"ng-component\"]],\n hostAttrs: [\"mat-ripple-style-loader\", \"\"],\n decls: 0,\n vars: 0,\n template: function _MatRippleStylesLoader_Template(rf, ctx) {},\n styles: [\".mat-ripple{overflow:hidden;position:relative}.mat-ripple:not(:empty){transform:translateZ(0)}.mat-ripple.mat-ripple-unbounded{overflow:visible}.mat-ripple-element{position:absolute;border-radius:50%;pointer-events:none;transition:opacity,transform 0ms cubic-bezier(0, 0, 0.2, 1);transform:scale3d(0, 0, 0);background-color:var(--mat-ripple-color, color-mix(in srgb, var(--mat-sys-on-surface) 10%, transparent))}@media(forced-colors: active){.mat-ripple-element{display:none}}.cdk-drag-preview .mat-ripple-element,.cdk-drag-placeholder .mat-ripple-element{display:none}\"],\n encapsulation: 2,\n changeDetection: 0\n });\n }\n return _MatRippleStylesLoader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Helper service that performs DOM manipulations. Not intended to be used outside this module.\n * The constructor takes a reference to the ripple directive's host element and a map of DOM\n * event handlers to be installed on the element that triggers ripple animations.\n * This will eventually become a custom renderer once Angular support exists.\n * @docs-private\n */\nclass RippleRenderer {\n _target;\n _ngZone;\n _platform;\n /** Element where the ripples are being added to. */\n _containerElement;\n /** Element which triggers the ripple elements on mouse events. */\n _triggerElement;\n /** Whether the pointer is currently down or not. */\n _isPointerDown = false;\n /**\n * Map of currently active ripple references.\n * The ripple reference is mapped to its element event listeners.\n * The reason why `| null` is used is that event listeners are added only\n * when the condition is truthy (see the `_startFadeOutTransition` method).\n */\n _activeRipples = /*#__PURE__*/new Map();\n /** Latest non-persistent ripple that was triggered. */\n _mostRecentTransientRipple;\n /** Time in milliseconds when the last touchstart event happened. */\n _lastTouchStartEvent;\n /** Whether pointer-up event listeners have been registered. */\n _pointerUpEventsRegistered = false;\n /**\n * Cached dimensions of the ripple container. Set when the first\n * ripple is shown and cleared once no more ripples are visible.\n */\n _containerRect;\n static _eventManager = /*#__PURE__*/new RippleEventManager();\n constructor(_target, _ngZone, elementOrElementRef, _platform, injector) {\n this._target = _target;\n this._ngZone = _ngZone;\n this._platform = _platform;\n // Only do anything if we're on the browser.\n if (_platform.isBrowser) {\n this._containerElement = coerceElement(elementOrElementRef);\n }\n if (injector) {\n injector.get(_CdkPrivateStyleLoader).load(_MatRippleStylesLoader);\n }\n }\n /**\n * Fades in a ripple at the given coordinates.\n * @param x Coordinate within the element, along the X axis at which to start the ripple.\n * @param y Coordinate within the element, along the Y axis at which to start the ripple.\n * @param config Extra ripple options.\n */\n fadeInRipple(x, y, config = {}) {\n const containerRect = this._containerRect = this._containerRect || this._containerElement.getBoundingClientRect();\n const animationConfig = {\n ...defaultRippleAnimationConfig,\n ...config.animation\n };\n if (config.centered) {\n x = containerRect.left + containerRect.width / 2;\n y = containerRect.top + containerRect.height / 2;\n }\n const radius = config.radius || distanceToFurthestCorner(x, y, containerRect);\n const offsetX = x - containerRect.left;\n const offsetY = y - containerRect.top;\n const enterDuration = animationConfig.enterDuration;\n const ripple = document.createElement('div');\n ripple.classList.add('mat-ripple-element');\n ripple.style.left = `${offsetX - radius}px`;\n ripple.style.top = `${offsetY - radius}px`;\n ripple.style.height = `${radius * 2}px`;\n ripple.style.width = `${radius * 2}px`;\n // If a custom color has been specified, set it as inline style. If no color is\n // set, the default color will be applied through the ripple theme styles.\n if (config.color != null) {\n ripple.style.backgroundColor = config.color;\n }\n ripple.style.transitionDuration = `${enterDuration}ms`;\n this._containerElement.appendChild(ripple);\n // By default the browser does not recalculate the styles of dynamically created\n // ripple elements. This is critical to ensure that the `scale` animates properly.\n // We enforce a style recalculation by calling `getComputedStyle` and *accessing* a property.\n // See: https://gist.github.com/paulirish/5d52fb081b3570c81e3a\n const computedStyles = window.getComputedStyle(ripple);\n const userTransitionProperty = computedStyles.transitionProperty;\n const userTransitionDuration = computedStyles.transitionDuration;\n // Note: We detect whether animation is forcibly disabled through CSS (e.g. through\n // `transition: none` or `display: none`). This is technically unexpected since animations are\n // controlled through the animation config, but this exists for backwards compatibility. This\n // logic does not need to be super accurate since it covers some edge cases which can be easily\n // avoided by users.\n const animationForciblyDisabledThroughCss = userTransitionProperty === 'none' ||\n // Note: The canonical unit for serialized CSS `