{"version":3,"file":"firebase-firestore-lite-pipelines.js","sources":["../util/src/errors.ts","../util/src/compat.ts","../logger/src/logger.ts","../../node_modules/closure-net/firebase/bloom_blob_es2018.js","../firestore/src/auth/user.ts","../firestore/src/core/version.ts","../firestore/src/util/log.ts","../firestore/src/platform/browser/format_json.ts","../firestore/src/util/assert.ts","../firestore/src/util/error.ts","../firestore/src/api/credentials.ts","../firestore/src/core/database_info.ts","../firestore/src/platform/browser/random_bytes.ts","../firestore/src/util/misc.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/util/input_validation.ts","../firestore/src/api/long_polling_options.ts","../firestore/src/util/debug_uid.ts","../firestore/src/util/types.ts","../firestore/src/remote/rest_connection.ts","../util/src/url.ts","../firestore/src/remote/rpc_error.ts","../firestore/src/platform/browser_lite/fetch_connection.ts","../firestore/src/util/obj.ts","../firestore/src/util/base64_decode_error.ts","../firestore/src/util/byte_string.ts","../firestore/src/platform/browser/base64.ts","../firestore/src/model/normalize.ts","../firestore/src/util/json_validation.ts","../firestore/src/lite-api/timestamp.ts","../firestore/src/model/server_timestamps.ts","../firestore/src/model/values.ts","../firestore/src/core/filter.ts","../firestore/src/core/order_by.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/object_value.ts","../firestore/src/core/query.ts","../firestore/src/remote/number_serializer.ts","../firestore/src/remote/serializer.ts","../firestore/src/platform/browser/serializer.ts","../firestore/src/remote/datastore.ts","../firestore/src/lite-api/components.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/lite-api/settings.ts","../firestore/src/local/lru_garbage_collector_impl.ts","../firestore/src/lite-api/database.ts","../firestore/src/lite-api/reference.ts","../firestore/src/lite-api/bytes.ts","../firestore/src/lite-api/field_path.ts","../firestore/src/lite-api/field_value.ts","../firestore/src/lite-api/geo_point.ts","../firestore/src/lite-api/vector_value.ts","../firestore/src/util/array.ts","../firestore/src/lite-api/user_data_reader.ts","../firestore/src/lite-api/user_data_writer.ts","../firestore/src/lite-api/reference_impl.ts","../firestore/src/lite-api/field_value_impl.ts","../firestore/src/core/options_util.ts","../firestore/src/core/structured_pipeline.ts","../firestore/src/util/proto.ts","../firestore/src/lite-api/expressions.ts","../firestore/src/core/pipeline-util.ts","../firestore/src/util/pipeline_util.ts","../firestore/src/lite-api/stage.ts","../firestore/src/lite-api/pipeline.ts","../firestore/src/lite-api/pipeline-source.ts","../firestore/src/lite-api/pipeline-result.ts","../firestore/src/lite-api/pipeline_impl.ts","../firestore/src/platform/browser_lite/connection.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n *   // TypeScript string literals for type-safe codes\n *   type Err =\n *     'unknown' |\n *     'object-not-found'\n *     ;\n *\n *   // Closure enum for type-safe error codes\n *   // at-enum {string}\n *   var Err = {\n *     UNKNOWN: 'unknown',\n *     OBJECT_NOT_FOUND: 'object-not-found',\n *   }\n *\n *   let errors: Map<Err, string> = {\n *     'generic-error': \"Unknown error\",\n *     'file-not-found': \"Could not find file: {$file}\",\n *   };\n *\n *   // Type-safe function - must pass a valid error code as param.\n *   let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n *   ...\n *   throw error.create(Err.GENERIC);\n *   ...\n *   throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n *   ...\n *   // Service: Could not file file: foo.txt (service/file-not-found).\n *\n *   catch (e) {\n *     assert(e.message === \"Could not find file: foo.txt.\");\n *     if ((e as FirebaseError)?.code === 'service/file-not-found') {\n *       console.log(\"Could not read file: \" + e['file']);\n *     }\n *   }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n  readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n  toString(): string;\n}\n\nexport interface ErrorData {\n  [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n  /** The custom name for all FirebaseErrors. */\n  readonly name: string = ERROR_NAME;\n\n  constructor(\n    /** The error code for this error. */\n    readonly code: string,\n    message: string,\n    /** Custom data for this error. */\n    public customData?: Record<string, unknown>\n  ) {\n    super(message);\n\n    // Fix For ES5\n    // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n    // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n    //                   which we can now use since we no longer target ES5.\n    Object.setPrototypeOf(this, FirebaseError.prototype);\n\n    // Maintains proper stack trace for where our error was thrown.\n    // Only available on V8.\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, ErrorFactory.prototype.create);\n    }\n  }\n}\n\nexport class ErrorFactory<\n  ErrorCode extends string,\n  ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n  constructor(\n    private readonly service: string,\n    private readonly serviceName: string,\n    private readonly errors: ErrorMap<ErrorCode>\n  ) {}\n\n  create<K extends ErrorCode>(\n    code: K,\n    ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n  ): FirebaseError {\n    const customData = (data[0] as ErrorData) || {};\n    const fullCode = `${this.service}/${code}`;\n    const template = this.errors[code];\n\n    const message = template ? replaceTemplate(template, customData) : 'Error';\n    // Service Name: Error message (service/code).\n    const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n    const error = new FirebaseError(fullCode, fullMessage, customData);\n\n    return error;\n  }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n  return template.replace(PATTERN, (_, key) => {\n    const value = data[key];\n    return value != null ? String(value) : `<${key}?>`;\n  });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n  _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n  service: Compat<ExpService> | ExpService\n): ExpService {\n  if (service && (service as Compat<ExpService>)._delegate) {\n    return (service as Compat<ExpService>)._delegate;\n  } else {\n    return service as ExpService;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n  | 'debug'\n  | 'verbose'\n  | 'info'\n  | 'warn'\n  | 'error'\n  | 'silent';\n\nexport interface LogOptions {\n  level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n  level: LogLevelString;\n  message: string;\n  args: unknown[];\n  type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n  DEBUG,\n  VERBOSE,\n  INFO,\n  WARN,\n  ERROR,\n  SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n  'debug': LogLevel.DEBUG,\n  'verbose': LogLevel.VERBOSE,\n  'info': LogLevel.INFO,\n  'warn': LogLevel.WARN,\n  'error': LogLevel.ERROR,\n  'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n  loggerInstance: Logger,\n  logType: LogLevel,\n  ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n  [LogLevel.DEBUG]: 'log',\n  [LogLevel.VERBOSE]: 'log',\n  [LogLevel.INFO]: 'info',\n  [LogLevel.WARN]: 'warn',\n  [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n  if (logType < instance.logLevel) {\n    return;\n  }\n  const now = new Date().toISOString();\n  const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n  if (method) {\n    console[method as 'log' | 'info' | 'warn' | 'error'](\n      `[${now}]  ${instance.name}:`,\n      ...args\n    );\n  } else {\n    throw new Error(\n      `Attempted to log a message with an invalid logType (value: ${logType})`\n    );\n  }\n};\n\nexport class Logger {\n  /**\n   * Gives you an instance of a Logger to capture messages according to\n   * Firebase's logging scheme.\n   *\n   * @param name The name that the logs will be associated with\n   */\n  constructor(public name: string) {\n    /**\n     * Capture the current instance for later use\n     */\n    instances.push(this);\n  }\n\n  /**\n   * The log level of the given Logger instance.\n   */\n  private _logLevel = defaultLogLevel;\n\n  get logLevel(): LogLevel {\n    return this._logLevel;\n  }\n\n  set logLevel(val: LogLevel) {\n    if (!(val in LogLevel)) {\n      throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n    }\n    this._logLevel = val;\n  }\n\n  // Workaround for setter/getter having to be the same type.\n  setLogLevel(val: LogLevel | LogLevelString): void {\n    this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n  }\n\n  /**\n   * The main (internal) log handler for the Logger instance.\n   * Can be set to a new function in internal package code but not by user.\n   */\n  private _logHandler: LogHandler = defaultLogHandler;\n  get logHandler(): LogHandler {\n    return this._logHandler;\n  }\n  set logHandler(val: LogHandler) {\n    if (typeof val !== 'function') {\n      throw new TypeError('Value assigned to `logHandler` must be a function');\n    }\n    this._logHandler = val;\n  }\n\n  /**\n   * The optional, additional, user-defined log handler for the Logger instance.\n   */\n  private _userLogHandler: LogHandler | null = null;\n  get userLogHandler(): LogHandler | null {\n    return this._userLogHandler;\n  }\n  set userLogHandler(val: LogHandler | null) {\n    this._userLogHandler = val;\n  }\n\n  /**\n   * The functions below are all based on the `console` interface\n   */\n\n  debug(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n    this._logHandler(this, LogLevel.DEBUG, ...args);\n  }\n  log(...args: unknown[]): void {\n    this._userLogHandler &&\n      this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n    this._logHandler(this, LogLevel.VERBOSE, ...args);\n  }\n  info(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n    this._logHandler(this, LogLevel.INFO, ...args);\n  }\n  warn(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n    this._logHandler(this, LogLevel.WARN, ...args);\n  }\n  error(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n    this._logHandler(this, LogLevel.ERROR, ...args);\n  }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n  instances.forEach(inst => {\n    inst.setLogLevel(level);\n  });\n}\n\nexport function setUserLogHandler(\n  logCallback: LogCallback | null,\n  options?: LogOptions\n): void {\n  for (const instance of instances) {\n    let customLogLevel: LogLevel | null = null;\n    if (options && options.level) {\n      customLogLevel = levelStringToEnum[options.level];\n    }\n    if (logCallback === null) {\n      instance.userLogHandler = null;\n    } else {\n      instance.userLogHandler = (\n        instance: Logger,\n        level: LogLevel,\n        ...args: unknown[]\n      ) => {\n        const message = args\n          .map(arg => {\n            if (arg == null) {\n              return null;\n            } else if (typeof arg === 'string') {\n              return arg;\n            } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n              return arg.toString();\n            } else if (arg instanceof Error) {\n              return arg.message;\n            } else {\n              try {\n                return JSON.stringify(arg);\n              } catch (ignored) {\n                return null;\n              }\n            }\n          })\n          .filter(arg => arg)\n          .join(' ');\n        if (level >= (customLogLevel ?? instance.logLevel)) {\n          logCallback({\n            level: LogLevel[level].toLowerCase() as LogLevelString,\n            message,\n            args,\n            type: instance.name\n          });\n        }\n      };\n    }\n  }\n}\n","/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h;/** @license\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\nfunction k(d,a){function c(){}c.prototype=a.prototype;d.F=a.prototype;d.prototype=new c;d.prototype.constructor=d;d.D=function(f,e,g){for(var b=Array(arguments.length-2),r=2;r<arguments.length;r++)b[r-2]=arguments[r];return a.prototype[e].apply(f,b)}};function l(){this.blockSize=-1};function m(){this.blockSize=-1;this.blockSize=64;this.g=Array(4);this.C=Array(this.blockSize);this.o=this.h=0;this.u()}k(m,l);m.prototype.u=function(){this.g[0]=1732584193;this.g[1]=4023233417;this.g[2]=2562383102;this.g[3]=271733878;this.o=this.h=0};\nfunction n(d,a,c){c||(c=0);const f=Array(16);if(typeof a===\"string\")for(var e=0;e<16;++e)f[e]=a.charCodeAt(c++)|a.charCodeAt(c++)<<8|a.charCodeAt(c++)<<16|a.charCodeAt(c++)<<24;else for(e=0;e<16;++e)f[e]=a[c++]|a[c++]<<8|a[c++]<<16|a[c++]<<24;a=d.g[0];c=d.g[1];e=d.g[2];let g=d.g[3],b;b=a+(g^c&(e^g))+f[0]+3614090360&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+f[1]+3905402710&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+f[2]+606105819&4294967295;e=g+(b<<17&4294967295|b>>>15);\nb=c+(a^e&(g^a))+f[3]+3250441966&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+f[4]+4118548399&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+f[5]+1200080426&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+f[6]+2821735955&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+f[7]+4249261313&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+f[8]+1770035416&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+f[9]+2336552879&4294967295;g=a+(b<<12&4294967295|\nb>>>20);b=e+(c^g&(a^c))+f[10]+4294925233&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+f[11]+2304563134&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+f[12]+1804603682&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+f[13]+4254626195&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+f[14]+2792965006&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+f[15]+1236535329&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(e^g&(c^e))+f[1]+4129170786&4294967295;a=c+(b<<\n5&4294967295|b>>>27);b=g+(c^e&(a^c))+f[6]+3225465664&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+f[11]+643717713&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+f[0]+3921069994&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+f[5]+3593408605&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+f[10]+38016083&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+f[15]+3634488961&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+f[4]+3889429448&4294967295;c=\ne+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+f[9]+568446438&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+f[14]+3275163606&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+f[3]+4107603335&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+f[8]+1163531501&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+f[13]+2850285829&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+f[2]+4243563512&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+f[7]+1735328473&4294967295;\ne=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+f[12]+2368359562&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(c^e^g)+f[5]+4294588738&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+f[8]+2272392833&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+f[11]+1839030562&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+f[14]+4259657740&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+f[1]+2763975236&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+f[4]+1272893353&4294967295;g=a+(b<<11&4294967295|\nb>>>21);b=e+(g^a^c)+f[7]+4139469664&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+f[10]+3200236656&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+f[13]+681279174&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+f[0]+3936430074&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+f[3]+3572445317&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+f[6]+76029189&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+f[9]+3654602809&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+f[12]+\n3873151461&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+f[15]+530742520&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+f[2]+3299628645&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(e^(c|~g))+f[0]+4096336452&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+f[7]+1126891415&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+f[14]+2878612391&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+f[5]+4237533241&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+f[12]+1700485571&\n4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+f[3]+2399980690&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+f[10]+4293915773&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+f[1]+2240044497&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+f[8]+1873313359&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+f[15]+4264355552&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+f[6]+2734768916&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+f[13]+1309151649&\n4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+f[4]+4149444226&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+f[11]+3174756917&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+f[2]+718787259&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+f[9]+3951481745&4294967295;d.g[0]=d.g[0]+a&4294967295;d.g[1]=d.g[1]+(e+(b<<21&4294967295|b>>>11))&4294967295;d.g[2]=d.g[2]+e&4294967295;d.g[3]=d.g[3]+g&4294967295}\nm.prototype.v=function(d,a){a===void 0&&(a=d.length);const c=a-this.blockSize,f=this.C;let e=this.h,g=0;for(;g<a;){if(e==0)for(;g<=c;)n(this,d,g),g+=this.blockSize;if(typeof d===\"string\")for(;g<a;){if(f[e++]=d.charCodeAt(g++),e==this.blockSize){n(this,f);e=0;break}}else for(;g<a;)if(f[e++]=d[g++],e==this.blockSize){n(this,f);e=0;break}}this.h=e;this.o+=a};\nm.prototype.A=function(){var d=Array((this.h<56?this.blockSize:this.blockSize*2)-this.h);d[0]=128;for(var a=1;a<d.length-8;++a)d[a]=0;a=this.o*8;for(var c=d.length-8;c<d.length;++c)d[c]=a&255,a/=256;this.v(d);d=Array(16);a=0;for(c=0;c<4;++c)for(let f=0;f<32;f+=8)d[a++]=this.g[c]>>>f&255;return d};function p(d,a){var c=q;return Object.prototype.hasOwnProperty.call(c,d)?c[d]:c[d]=a(d)};function t(d,a){this.h=a;const c=[];let f=!0;for(let e=d.length-1;e>=0;e--){const g=d[e]|0;f&&g==a||(c[e]=g,f=!1)}this.g=c}var q={};function u(d){return-128<=d&&d<128?p(d,function(a){return new t([a|0],a<0?-1:0)}):new t([d|0],d<0?-1:0)}function v(d){if(isNaN(d)||!isFinite(d))return w;if(d<0)return x(v(-d));const a=[];let c=1;for(let f=0;d>=c;f++)a[f]=d/c|0,c*=4294967296;return new t(a,0)}\nfunction y(d,a){if(d.length==0)throw Error(\"number format error: empty string\");a=a||10;if(a<2||36<a)throw Error(\"radix out of range: \"+a);if(d.charAt(0)==\"-\")return x(y(d.substring(1),a));if(d.indexOf(\"-\")>=0)throw Error('number format error: interior \"-\" character');const c=v(Math.pow(a,8));let f=w;for(let g=0;g<d.length;g+=8){var e=Math.min(8,d.length-g);const b=parseInt(d.substring(g,g+e),a);e<8?(e=v(Math.pow(a,e)),f=f.j(e).add(v(b))):(f=f.j(c),f=f.add(v(b)))}return f}var w=u(0),z=u(1),A=u(16777216);\nh=t.prototype;h.m=function(){if(B(this))return-x(this).m();let d=0,a=1;for(let c=0;c<this.g.length;c++){const f=this.i(c);d+=(f>=0?f:4294967296+f)*a;a*=4294967296}return d};\nh.toString=function(d){d=d||10;if(d<2||36<d)throw Error(\"radix out of range: \"+d);if(C(this))return\"0\";if(B(this))return\"-\"+x(this).toString(d);const a=v(Math.pow(d,6));var c=this;let f=\"\";for(;;){const e=D(c,a).g;c=F(c,e.j(a));let g=((c.g.length>0?c.g[0]:c.h)>>>0).toString(d);c=e;if(C(c))return g+f;for(;g.length<6;)g=\"0\"+g;f=g+f}};h.i=function(d){return d<0?0:d<this.g.length?this.g[d]:this.h};function C(d){if(d.h!=0)return!1;for(let a=0;a<d.g.length;a++)if(d.g[a]!=0)return!1;return!0}\nfunction B(d){return d.h==-1}h.l=function(d){d=F(this,d);return B(d)?-1:C(d)?0:1};function x(d){const a=d.g.length,c=[];for(let f=0;f<a;f++)c[f]=~d.g[f];return(new t(c,~d.h)).add(z)}h.abs=function(){return B(this)?x(this):this};h.add=function(d){const a=Math.max(this.g.length,d.g.length),c=[];let f=0;for(let e=0;e<=a;e++){let g=f+(this.i(e)&65535)+(d.i(e)&65535),b=(g>>>16)+(this.i(e)>>>16)+(d.i(e)>>>16);f=b>>>16;g&=65535;b&=65535;c[e]=b<<16|g}return new t(c,c[c.length-1]&-2147483648?-1:0)};\nfunction F(d,a){return d.add(x(a))}\nh.j=function(d){if(C(this)||C(d))return w;if(B(this))return B(d)?x(this).j(x(d)):x(x(this).j(d));if(B(d))return x(this.j(x(d)));if(this.l(A)<0&&d.l(A)<0)return v(this.m()*d.m());const a=this.g.length+d.g.length,c=[];for(var f=0;f<2*a;f++)c[f]=0;for(f=0;f<this.g.length;f++)for(let e=0;e<d.g.length;e++){const g=this.i(f)>>>16,b=this.i(f)&65535,r=d.i(e)>>>16,E=d.i(e)&65535;c[2*f+2*e]+=b*E;G(c,2*f+2*e);c[2*f+2*e+1]+=g*E;G(c,2*f+2*e+1);c[2*f+2*e+1]+=b*r;G(c,2*f+2*e+1);c[2*f+2*e+2]+=g*r;G(c,2*f+2*e+2)}for(d=\n0;d<a;d++)c[d]=c[2*d+1]<<16|c[2*d];for(d=a;d<2*a;d++)c[d]=0;return new t(c,0)};function G(d,a){for(;(d[a]&65535)!=d[a];)d[a+1]+=d[a]>>>16,d[a]&=65535,a++}function H(d,a){this.g=d;this.h=a}\nfunction D(d,a){if(C(a))throw Error(\"division by zero\");if(C(d))return new H(w,w);if(B(d))return a=D(x(d),a),new H(x(a.g),x(a.h));if(B(a))return a=D(d,x(a)),new H(x(a.g),a.h);if(d.g.length>30){if(B(d)||B(a))throw Error(\"slowDivide_ only works with positive integers.\");for(var c=z,f=a;f.l(d)<=0;)c=I(c),f=I(f);var e=J(c,1),g=J(f,1);f=J(f,2);for(c=J(c,2);!C(f);){var b=g.add(f);b.l(d)<=0&&(e=e.add(c),g=b);f=J(f,1);c=J(c,1)}a=F(d,e.j(a));return new H(e,a)}for(e=w;d.l(a)>=0;){c=Math.max(1,Math.floor(d.m()/\na.m()));f=Math.ceil(Math.log(c)/Math.LN2);f=f<=48?1:Math.pow(2,f-48);g=v(c);for(b=g.j(a);B(b)||b.l(d)>0;)c-=f,g=v(c),b=g.j(a);C(g)&&(g=z);e=e.add(g);d=F(d,b)}return new H(e,d)}h.B=function(d){return D(this,d).h};h.and=function(d){const a=Math.max(this.g.length,d.g.length),c=[];for(let f=0;f<a;f++)c[f]=this.i(f)&d.i(f);return new t(c,this.h&d.h)};h.or=function(d){const a=Math.max(this.g.length,d.g.length),c=[];for(let f=0;f<a;f++)c[f]=this.i(f)|d.i(f);return new t(c,this.h|d.h)};\nh.xor=function(d){const a=Math.max(this.g.length,d.g.length),c=[];for(let f=0;f<a;f++)c[f]=this.i(f)^d.i(f);return new t(c,this.h^d.h)};function I(d){const a=d.g.length+1,c=[];for(let f=0;f<a;f++)c[f]=d.i(f)<<1|d.i(f-1)>>>31;return new t(c,d.h)}function J(d,a){const c=a>>5;a%=32;const f=d.g.length-c,e=[];for(let g=0;g<f;g++)e[g]=a>0?d.i(g+c)>>>a|d.i(g+c+1)<<32-a:d.i(g+c);return new t(e,d.h)};m.prototype.digest=m.prototype.A;m.prototype.reset=m.prototype.u;m.prototype.update=m.prototype.v;module.exports.Md5=m;t.prototype.add=t.prototype.add;t.prototype.multiply=t.prototype.j;t.prototype.modulo=t.prototype.B;t.prototype.compare=t.prototype.l;t.prototype.toNumber=t.prototype.m;t.prototype.toString=t.prototype.toString;t.prototype.getBits=t.prototype.i;t.fromNumber=v;t.fromString=y;module.exports.Integer=t;}).apply( typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self  : typeof window !== 'undefined' ? window  : {});\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n  /** A user with a null UID. */\n  static readonly UNAUTHENTICATED = new User(null);\n\n  // TODO(mikelehen): Look into getting a proper uid-equivalent for\n  // non-FirebaseAuth providers.\n  static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n  static readonly FIRST_PARTY = new User('first-party-uid');\n  static readonly MOCK_USER = new User('mock-user');\n\n  constructor(readonly uid: string | null) {}\n\n  isAuthenticated(): boolean {\n    return this.uid != null;\n  }\n\n  /**\n   * Returns a key representing this user, suitable for inclusion in a\n   * dictionary.\n   */\n  toKey(): string {\n    if (this.isAuthenticated()) {\n      return 'uid:' + this.uid;\n    } else {\n      return 'anonymous-user';\n    }\n  }\n\n  isEqual(otherUser: User): boolean {\n    return otherUser.uid === this.uid;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n  SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n  return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n *   be any of the following values:\n *\n *   <ul>\n *     <li>`debug` for the most verbose logging level, primarily for\n *     debugging.</li>\n *     <li>`error` to log errors only.</li>\n *     <li><code>`silent` to turn off logging.</li>\n *   </ul>\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n  logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n  if (logClient.logLevel <= LogLevel.DEBUG) {\n    const args = obj.map(argToString);\n    logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n  }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n  if (logClient.logLevel <= LogLevel.ERROR) {\n    const args = obj.map(argToString);\n    logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n  }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n  if (logClient.logLevel <= LogLevel.WARN) {\n    const args = obj.map(argToString);\n    logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n  }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n  if (typeof obj === 'string') {\n    return obj;\n  } else {\n    try {\n      return formatJSON(obj);\n    } catch (e) {\n      // Converting to JSON failed, just log the object directly\n      return obj;\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n  return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param code - generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n  code: number,\n  message: string,\n  context?: Record<string, unknown>\n): never;\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param id - generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record<string, unknown>): never;\n\nexport function fail(\n  id: number,\n  messageOrContext?: string | Record<string, unknown>,\n  context?: Record<string, unknown>\n): never {\n  let message = 'Unexpected state';\n  if (typeof messageOrContext === 'string') {\n    message = messageOrContext;\n  } else {\n    context = messageOrContext;\n  }\n  _fail(id, message, context);\n}\n\nfunction _fail(\n  id: number,\n  failure: string,\n  context?: Record<string, unknown>\n): never {\n  // Log the failure in addition to throw an exception, just in case the\n  // exception is swallowed.\n  let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n    16\n  )})`;\n  if (context !== undefined) {\n    try {\n      const stringContext = JSON.stringify(context);\n      message += ' CONTEXT: ' + stringContext;\n    } catch (e) {\n      message += ' CONTEXT: ' + context;\n    }\n  }\n  logError(message);\n\n  // NOTE: We don't use FirestoreError here because these are internal failures\n  // that cannot be handled by the user. (Also it would create a circular\n  // dependency between the error and assert modules which doesn't work.)\n  throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id - generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n  assertion: boolean,\n  id: number,\n  message: string,\n  context?: Record<string, unknown>\n): asserts assertion;\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id - generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n  assertion: boolean,\n  id: number,\n  context?: Record<string, unknown>\n): asserts assertion;\n\nexport function hardAssert(\n  assertion: boolean,\n  id: number,\n  messageOrContext?: string | Record<string, unknown>,\n  context?: Record<string, unknown>\n): asserts assertion {\n  let message = 'Unexpected state';\n  if (typeof messageOrContext === 'string') {\n    message = messageOrContext;\n  } else {\n    context = messageOrContext;\n  }\n\n  if (!assertion) {\n    _fail(id, message, context);\n  }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n  assertion: boolean,\n  message: string\n): asserts assertion {\n  if (!assertion) {\n    fail(0xdeb6, message);\n  }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast<T>(\n  obj: object,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor: { new (...args: any[]): T }\n): T | never {\n  debugAssert(\n    obj instanceof constructor,\n    `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n  );\n  return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n *   differs from 'failed-precondition'. 'invalid-argument' indicates\n *   arguments that are problematic regardless of the state of the system\n *   (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n *   For operations that change the state of the system, this error may be\n *   returned even if the operation has completed successfully. For example,\n *   a successful response from a server could have been delayed long enough\n *   for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n *   exists.\n * - 'permission-denied': The caller does not have permission to execute the\n *   specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n *   per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n *   in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n *   issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n *   underlying system has been broken. If you see one of these errors,\n *   something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n *   a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n *   credentials for the operation.\n */\nexport type FirestoreErrorCode =\n  | 'cancelled'\n  | 'unknown'\n  | 'invalid-argument'\n  | 'deadline-exceeded'\n  | 'not-found'\n  | 'already-exists'\n  | 'permission-denied'\n  | 'resource-exhausted'\n  | 'failed-precondition'\n  | 'aborted'\n  | 'out-of-range'\n  | 'unimplemented'\n  | 'internal'\n  | 'unavailable'\n  | 'data-loss'\n  | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n  // Causes are copied from:\n  // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n  /** Not an error; returned on success. */\n  OK: 'ok' as FirestoreErrorCode,\n\n  /** The operation was cancelled (typically by the caller). */\n  CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n  /** Unknown error or an error from a different error domain. */\n  UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n  /**\n   * Client specified an invalid argument. Note that this differs from\n   * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n   * problematic regardless of the state of the system (e.g., a malformed file\n   * name).\n   */\n  INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n  /**\n   * Deadline expired before operation could complete. For operations that\n   * change the state of the system, this error may be returned even if the\n   * operation has completed successfully. For example, a successful response\n   * from a server could have been delayed long enough for the deadline to\n   * expire.\n   */\n  DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n  /** Some requested entity (e.g., file or directory) was not found. */\n  NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n  /**\n   * Some entity that we attempted to create (e.g., file or directory) already\n   * exists.\n   */\n  ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n  /**\n   * The caller does not have permission to execute the specified operation.\n   * PERMISSION_DENIED must not be used for rejections caused by exhausting\n   * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n   * PERMISSION_DENIED must not be used if the caller cannot be identified\n   * (use UNAUTHENTICATED instead for those errors).\n   */\n  PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n  /**\n   * The request does not have valid authentication credentials for the\n   * operation.\n   */\n  UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n  /**\n   * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n   * entire file system is out of space.\n   */\n  RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n  /**\n   * Operation was rejected because the system is not in a state required for\n   * the operation's execution. For example, directory to be deleted may be\n   * non-empty, an rmdir operation is applied to a non-directory, etc.\n   *\n   * A litmus test that may help a service implementor in deciding\n   * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n   *  (a) Use UNAVAILABLE if the client can retry just the failing call.\n   *  (b) Use ABORTED if the client should retry at a higher-level\n   *      (e.g., restarting a read-modify-write sequence).\n   *  (c) Use FAILED_PRECONDITION if the client should not retry until\n   *      the system state has been explicitly fixed. E.g., if an \"rmdir\"\n   *      fails because the directory is non-empty, FAILED_PRECONDITION\n   *      should be returned since the client should not retry unless\n   *      they have first fixed up the directory by deleting files from it.\n   *  (d) Use FAILED_PRECONDITION if the client performs conditional\n   *      REST Get/Update/Delete on a resource and the resource on the\n   *      server does not match the condition. E.g., conflicting\n   *      read-modify-write on the same resource.\n   */\n  FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n  /**\n   * The operation was aborted, typically due to a concurrency issue like\n   * sequencer check failures, transaction aborts, etc.\n   *\n   * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n   * and UNAVAILABLE.\n   */\n  ABORTED: 'aborted' as FirestoreErrorCode,\n\n  /**\n   * Operation was attempted past the valid range. E.g., seeking or reading\n   * past end of file.\n   *\n   * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n   * if the system state changes. For example, a 32-bit file system will\n   * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n   * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n   * an offset past the current file size.\n   *\n   * There is a fair bit of overlap between FAILED_PRECONDITION and\n   * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n   * when it applies so that callers who are iterating through a space can\n   * easily look for an OUT_OF_RANGE error to detect when they are done.\n   */\n  OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n  /** Operation is not implemented or not supported/enabled in this service. */\n  UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n  /**\n   * Internal errors. Means some invariants expected by underlying System has\n   * been broken. If you see one of these errors, Something is very broken.\n   */\n  INTERNAL: 'internal' as FirestoreErrorCode,\n\n  /**\n   * The service is currently unavailable. This is a most likely a transient\n   * condition and may be corrected by retrying with a backoff.\n   *\n   * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n   * and UNAVAILABLE.\n   */\n  UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n  /** Unrecoverable data loss or corruption. */\n  DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n  /** The stack of the error. */\n  readonly stack?: string;\n\n  /** @hideconstructor */\n  constructor(\n    /**\n     * The backend error code associated with this error.\n     */\n    readonly code: FirestoreErrorCode,\n    /**\n     * A custom error description.\n     */\n    readonly message: string\n  ) {\n    super(code, message);\n\n    // HACK: We write a toString property directly because Error is not a real\n    // class and so inheritance does not work correctly. We could alternatively\n    // do the same \"back-door inheritance\" trick that FirebaseError does.\n    this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n  AppCheckInternalComponentName,\n  AppCheckTokenListener,\n  AppCheckTokenResult,\n  FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n  FirebaseAuthInternal,\n  FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n  // These are external types. Prevent minification.\n  ['type']: 'firstParty';\n  ['sessionIndex']: string;\n  ['iamToken']: string | null;\n  ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n  // These are external types. Prevent minification.\n  ['type']: 'provider';\n  ['client']: CredentialsProvider<User>;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n  | FirstPartyCredentialsSettings\n  | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n  /** Type of token. */\n  type: TokenType;\n\n  /**\n   * The user with which the token is associated (used for persisting user\n   * state on disk, etc.).\n   * This will be null for Tokens of the type 'AppCheck'.\n   */\n  user?: User;\n\n  /** Header values to set for this token */\n  headers: Map<string, string>;\n}\n\nexport class OAuthToken implements Token {\n  type = 'OAuth' as TokenType;\n  headers = new Map();\n\n  constructor(value: string, public user: User) {\n    this.headers.set('Authorization', `Bearer ${value}`);\n  }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener<T> = (credential: T) => Promise<void>;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider<T> {\n  /**\n   * Starts the credentials provider and specifies a listener to be notified of\n   * credential changes (sign-in / sign-out, token changes). It is immediately\n   * called once with the initial user.\n   *\n   * The change listener is invoked on the provided AsyncQueue.\n   */\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<T>\n  ): void;\n\n  /** Requests a token for the current user. */\n  getToken(): Promise<Token | null>;\n\n  /**\n   * Marks the last retrieved token as invalid, making the next GetToken request\n   * force-refresh the token.\n   */\n  invalidateToken(): void;\n\n  shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {\n  getToken(): Promise<Token | null> {\n    return Promise.resolve<Token | null>(null);\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    // Fire with initial user.\n    asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n  }\n\n  shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n  implements CredentialsProvider<User>\n{\n  constructor(private token: Token) {}\n\n  /**\n   * Stores the listener registered with setChangeListener()\n   * This isn't actually necessary since the UID never changes, but we use this\n   * to verify the listen contract is adhered to in tests.\n   */\n  private changeListener: CredentialChangeListener<User> | null = null;\n\n  getToken(): Promise<Token | null> {\n    return Promise.resolve(this.token);\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    debugAssert(\n      !this.changeListener,\n      'Can only call setChangeListener() once.'\n    );\n    this.changeListener = changeListener;\n    // Fire with initial user.\n    asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n  }\n\n  shutdown(): void {\n    this.changeListener = null;\n  }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider<User> {\n  private auth: FirebaseAuthInternal | null = null;\n\n  constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n    authProvider.onInit(auth => {\n      this.auth = auth;\n    });\n  }\n\n  getToken(): Promise<Token | null> {\n    if (!this.auth) {\n      return Promise.resolve(null);\n    }\n\n    return this.auth.getToken().then(tokenData => {\n      if (tokenData) {\n        hardAssert(\n          typeof tokenData.accessToken === 'string',\n          0xa539,\n          'Invalid tokenData returned from getToken()',\n          { tokenData }\n        );\n        return new OAuthToken(\n          tokenData.accessToken,\n          new User(this.auth!.getUid())\n        );\n      } else {\n        return null;\n      }\n    });\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {}\n\n  shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n  implements CredentialsProvider<User>\n{\n  /**\n   * The auth token listener registered with FirebaseApp, retained here so we\n   * can unregister it.\n   */\n  private tokenListener: (() => void) | undefined;\n\n  /** Tracks the current User. */\n  private currentUser: User = User.UNAUTHENTICATED;\n\n  /**\n   * Counter used to detect if the token changed while a getToken request was\n   * outstanding.\n   */\n  private tokenCounter = 0;\n\n  private forceRefresh = false;\n\n  private auth: FirebaseAuthInternal | null = null;\n\n  constructor(private authProvider: Provider<FirebaseAuthInternalName>) {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    hardAssert(\n      this.tokenListener === undefined,\n      0xa540,\n      'Token listener already added'\n    );\n    let lastTokenId = this.tokenCounter;\n\n    // A change listener that prevents double-firing for the same token change.\n    const guardedChangeListener: (user: User) => Promise<void> = user => {\n      if (this.tokenCounter !== lastTokenId) {\n        lastTokenId = this.tokenCounter;\n        return changeListener(user);\n      } else {\n        return Promise.resolve();\n      }\n    };\n\n    // A promise that can be waited on to block on the next token change.\n    // This promise is re-created after each change.\n    let nextToken = new Deferred<void>();\n\n    this.tokenListener = () => {\n      this.tokenCounter++;\n      this.currentUser = this.getUser();\n      nextToken.resolve();\n      nextToken = new Deferred<void>();\n      asyncQueue.enqueueRetryable(() =>\n        guardedChangeListener(this.currentUser)\n      );\n    };\n\n    const awaitNextToken: () => void = () => {\n      const currentTokenAttempt = nextToken;\n      asyncQueue.enqueueRetryable(async () => {\n        await currentTokenAttempt.promise;\n        await guardedChangeListener(this.currentUser);\n      });\n    };\n\n    const registerAuth = (auth: FirebaseAuthInternal): void => {\n      logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n      this.auth = auth;\n      if (this.tokenListener) {\n        this.auth.addAuthTokenListener(this.tokenListener);\n        awaitNextToken();\n      }\n    };\n\n    this.authProvider.onInit(auth => registerAuth(auth));\n\n    // Our users can initialize Auth right after Firestore, so we give it\n    // a chance to register itself with the component framework before we\n    // determine whether to start up in unauthenticated mode.\n    setTimeout(() => {\n      if (!this.auth) {\n        const auth = this.authProvider.getImmediate({ optional: true });\n        if (auth) {\n          registerAuth(auth);\n        } else {\n          // If auth is still not available, proceed with `null` user\n          logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n          nextToken.resolve();\n          nextToken = new Deferred<void>();\n        }\n      }\n    }, 0);\n\n    awaitNextToken();\n  }\n\n  getToken(): Promise<Token | null> {\n    debugAssert(\n      this.tokenListener != null,\n      'FirebaseAuthCredentialsProvider not started.'\n    );\n\n    // Take note of the current value of the tokenCounter so that this method\n    // can fail (with an ABORTED error) if there is a token change while the\n    // request is outstanding.\n    const initialTokenCounter = this.tokenCounter;\n    const forceRefresh = this.forceRefresh;\n    this.forceRefresh = false;\n\n    if (!this.auth) {\n      return Promise.resolve(null);\n    }\n\n    return this.auth.getToken(forceRefresh).then(tokenData => {\n      // Cancel the request since the token changed while the request was\n      // outstanding so the response is potentially for a previous user (which\n      // user, we can't be sure).\n      if (this.tokenCounter !== initialTokenCounter) {\n        logDebug(\n          'FirebaseAuthCredentialsProvider',\n          'getToken aborted due to token change.'\n        );\n        return this.getToken();\n      } else {\n        if (tokenData) {\n          hardAssert(\n            typeof tokenData.accessToken === 'string',\n            0x7c5d,\n            'Invalid tokenData returned from getToken()',\n            { tokenData }\n          );\n          return new OAuthToken(tokenData.accessToken, this.currentUser);\n        } else {\n          return null;\n        }\n      }\n    });\n  }\n\n  invalidateToken(): void {\n    this.forceRefresh = true;\n  }\n\n  shutdown(): void {\n    if (this.auth && this.tokenListener) {\n      this.auth.removeAuthTokenListener(this.tokenListener);\n    }\n    this.tokenListener = undefined;\n  }\n\n  // Auth.getUid() can return null even with a user logged in. It is because\n  // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n  // This method should only be called in the AuthTokenListener callback\n  // to guarantee to get the actual user.\n  private getUser(): User {\n    const currentUid = this.auth && this.auth.getUid();\n    hardAssert(\n      currentUid === null || typeof currentUid === 'string',\n      0x0807,\n      'Received invalid UID',\n      { currentUid }\n    );\n    return new User(currentUid);\n  }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n  type = 'FirstParty' as TokenType;\n  user = User.FIRST_PARTY;\n  private _headers = new Map();\n\n  constructor(\n    private readonly sessionIndex: string,\n    private readonly iamToken: string | null,\n    private readonly authTokenFactory: AuthTokenFactory | null\n  ) {}\n\n  /**\n   * Gets an authorization token, using a provided factory function, or return\n   * null.\n   */\n  private getAuthToken(): string | null {\n    if (this.authTokenFactory) {\n      return this.authTokenFactory();\n    } else {\n      return null;\n    }\n  }\n\n  get headers(): Map<string, string> {\n    this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n    // Use array notation to prevent minification\n    const authHeaderTokenValue = this.getAuthToken();\n    if (authHeaderTokenValue) {\n      this._headers.set('Authorization', authHeaderTokenValue);\n    }\n    if (this.iamToken) {\n      this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n    }\n\n    return this._headers;\n  }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n  implements CredentialsProvider<User>\n{\n  constructor(\n    private sessionIndex: string,\n    private iamToken: string | null,\n    private authTokenFactory: AuthTokenFactory | null\n  ) {}\n\n  getToken(): Promise<Token | null> {\n    return Promise.resolve(\n      new FirstPartyToken(\n        this.sessionIndex,\n        this.iamToken,\n        this.authTokenFactory\n      )\n    );\n  }\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<User>\n  ): void {\n    // Fire with initial uid.\n    asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n  }\n\n  shutdown(): void {}\n\n  invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n  type = 'AppCheck' as TokenType;\n  headers = new Map();\n\n  constructor(private value: string) {\n    if (value && value.length > 0) {\n      this.headers.set('x-firebase-appcheck', this.value);\n    }\n  }\n}\n\nexport class FirebaseAppCheckTokenProvider\n  implements CredentialsProvider<string>\n{\n  /**\n   * The AppCheck token listener registered with FirebaseApp, retained here so\n   * we can unregister it.\n   */\n  private tokenListener: AppCheckTokenListener | undefined;\n  private forceRefresh = false;\n  private appCheck: FirebaseAppCheckInternal | null = null;\n  private latestAppCheckToken: string | null = null;\n  private serverAppAppCheckToken: string | null = null;\n\n  constructor(\n    app: FirebaseApp,\n    private appCheckProvider: Provider<AppCheckInternalComponentName>\n  ) {\n    if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n      this.serverAppAppCheckToken = app.settings.appCheckToken;\n    }\n  }\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<string>\n  ): void {\n    hardAssert(\n      this.tokenListener === undefined,\n      0x0db8,\n      'Token listener already added'\n    );\n\n    const onTokenChanged: (\n      tokenResult: AppCheckTokenResult\n    ) => Promise<void> = tokenResult => {\n      if (tokenResult.error != null) {\n        logDebug(\n          'FirebaseAppCheckTokenProvider',\n          `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n        );\n      }\n      const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n      this.latestAppCheckToken = tokenResult.token;\n      logDebug(\n        'FirebaseAppCheckTokenProvider',\n        `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n      );\n      return tokenUpdated\n        ? changeListener(tokenResult.token)\n        : Promise.resolve();\n    };\n\n    this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n      asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n    };\n\n    const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n      logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n      this.appCheck = appCheck;\n      if (this.tokenListener) {\n        this.appCheck.addTokenListener(this.tokenListener);\n      }\n    };\n\n    this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n    // Our users can initialize AppCheck after Firestore, so we give it\n    // a chance to register itself with the component framework.\n    setTimeout(() => {\n      if (!this.appCheck) {\n        const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n        if (appCheck) {\n          registerAppCheck(appCheck);\n        } else {\n          // If AppCheck is still not available, proceed without it.\n          logDebug(\n            'FirebaseAppCheckTokenProvider',\n            'AppCheck not yet detected'\n          );\n        }\n      }\n    }, 0);\n  }\n\n  getToken(): Promise<Token | null> {\n    if (this.serverAppAppCheckToken) {\n      return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n    }\n    debugAssert(\n      this.tokenListener != null,\n      'FirebaseAppCheckTokenProvider not started.'\n    );\n\n    const forceRefresh = this.forceRefresh;\n    this.forceRefresh = false;\n\n    if (!this.appCheck) {\n      return Promise.resolve(null);\n    }\n\n    return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n      if (tokenResult) {\n        hardAssert(\n          typeof tokenResult.token === 'string',\n          0xae0e,\n          'Invalid tokenResult returned from getToken()',\n          { tokenResult }\n        );\n        this.latestAppCheckToken = tokenResult.token;\n        return new AppCheckToken(tokenResult.token);\n      } else {\n        return null;\n      }\n    });\n  }\n\n  invalidateToken(): void {\n    this.forceRefresh = true;\n  }\n\n  shutdown(): void {\n    if (this.appCheck && this.tokenListener) {\n      this.appCheck.removeTokenListener(this.tokenListener);\n    }\n    this.tokenListener = undefined;\n  }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider<string> {\n  getToken(): Promise<Token | null> {\n    return Promise.resolve<Token | null>(new AppCheckToken(''));\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<string>\n  ): void {}\n\n  shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider<string> {\n  private appCheck: FirebaseAppCheckInternal | null = null;\n  private serverAppAppCheckToken: string | null = null;\n\n  constructor(\n    app: FirebaseApp,\n    private appCheckProvider: Provider<AppCheckInternalComponentName>\n  ) {\n    if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n      this.serverAppAppCheckToken = app.settings.appCheckToken;\n    }\n    appCheckProvider.onInit(appCheck => {\n      this.appCheck = appCheck;\n    });\n  }\n\n  getToken(): Promise<Token | null> {\n    if (this.serverAppAppCheckToken) {\n      return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n    }\n\n    if (!this.appCheck) {\n      return Promise.resolve(null);\n    }\n\n    return this.appCheck.getToken().then(tokenResult => {\n      if (tokenResult) {\n        hardAssert(\n          typeof tokenResult.token === 'string',\n          0x0d8e,\n          'Invalid tokenResult returned from getToken()',\n          { tokenResult }\n        );\n        return new AppCheckToken(tokenResult.token);\n      } else {\n        return null;\n      }\n    });\n  }\n\n  invalidateToken(): void {}\n\n  start(\n    asyncQueue: AsyncQueue,\n    changeListener: CredentialChangeListener<string>\n  ): void {}\n\n  shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n  credentials?: CredentialsSettings\n): CredentialsProvider<User> {\n  if (!credentials) {\n    return new EmptyAuthCredentialsProvider();\n  }\n  switch (credentials['type']) {\n    case 'firstParty':\n      return new FirstPartyAuthCredentialsProvider(\n        credentials['sessionIndex'] || '0',\n        credentials['iamToken'] || null,\n        credentials['authTokenFactory'] || null\n      );\n\n    case 'provider':\n      return credentials['client'];\n\n    default:\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'makeAuthCredentialsProvider failed due to invalid credential type'\n      );\n  }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n  /**\n   * Constructs a DatabaseInfo using the provided host, databaseId and\n   * persistenceKey.\n   *\n   * @param databaseId - The database to use.\n   * @param appId - The Firebase App Id.\n   * @param persistenceKey - A unique identifier for this Firestore's local\n   * storage (used in conjunction with the databaseId).\n   * @param host - The Firestore backend host to connect to.\n   * @param ssl - Whether to use SSL when connecting.\n   * @param forceLongPolling - Whether to use the forceLongPolling option\n   * when using WebChannel as the network transport.\n   * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n   * option when using WebChannel as the network transport.\n   * @param longPollingOptions - Options that configure long-polling.\n   * @param useFetchStreams - Whether to use the Fetch API instead of\n   * XMLHTTPRequest\n   */\n  constructor(\n    readonly databaseId: DatabaseId,\n    readonly appId: string,\n    readonly persistenceKey: string,\n    readonly host: string,\n    readonly ssl: boolean,\n    readonly forceLongPolling: boolean,\n    readonly autoDetectLongPolling: boolean,\n    readonly longPollingOptions: ExperimentalLongPollingOptions,\n    readonly useFetchStreams: boolean,\n    readonly isUsingEmulator: boolean,\n    readonly apiKey: string | undefined\n  ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n  readonly database: string;\n  constructor(readonly projectId: string, database?: string) {\n    this.database = database ? database : DEFAULT_DATABASE_NAME;\n  }\n\n  static empty(): DatabaseId {\n    return new DatabaseId('', '');\n  }\n\n  get isDefaultDatabase(): boolean {\n    return this.database === DEFAULT_DATABASE_NAME;\n  }\n\n  isEqual(other: {}): boolean {\n    return (\n      other instanceof DatabaseId &&\n      other.projectId === this.projectId &&\n      other.database === this.database\n    );\n  }\n}\n\nexport function databaseIdFromApp(\n  app: FirebaseApp,\n  database?: string\n): DatabaseId {\n  if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      '\"projectId\" not provided in firebase.initializeApp.'\n    );\n  }\n\n  return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n  debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n  // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n  const crypto =\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n  const bytes = new Uint8Array(nBytes);\n  if (crypto && typeof crypto.getRandomValues === 'function') {\n    crypto.getRandomValues(bytes);\n  } else {\n    // Falls back to Math.random\n    for (let i = 0; i < nBytes; i++) {\n      bytes[i] = Math.floor(Math.random() * 256);\n    }\n  }\n  return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n  [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n  static newId(): string {\n    // Alphanumeric characters\n    const chars =\n      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n    // The largest byte value that is a multiple of `char.length`.\n    const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n    debugAssert(\n      0 < maxMultiple && maxMultiple < 256,\n      `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n    );\n\n    let autoId = '';\n    const targetLength = 20;\n    while (autoId.length < targetLength) {\n      const bytes = randomBytes(40);\n      for (let i = 0; i < bytes.length; ++i) {\n        // Only accept values that are [0, maxMultiple), this ensures they can\n        // be evenly mapped to indices of `chars` via a modulo operation.\n        if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n          autoId += chars.charAt(bytes[i] % chars.length);\n        }\n      }\n    }\n    debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n    return autoId;\n  }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n  if (left < right) {\n    return -1;\n  }\n  if (left > right) {\n    return 1;\n  }\n  return 0;\n}\n\nexport interface Equatable<T> {\n  isEqual(other: T): boolean;\n}\n\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n  // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n  // if found, use that character to determine the relative ordering of the two strings as a\n  // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n  // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n  // and UTF-16 happen to represent Unicode code points.\n  //\n  // After finding the first pair of differing characters, there are two cases:\n  //\n  // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n  // both are surrogates from a surrogate pair (that collectively represent code points greater\n  // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n  // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n  // sufficient.\n  //\n  // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n  // containing string is always ordered after the non-surrogate. This is because surrogates are\n  // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n  // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n  // less than or equal to 0xFFFF.\n  //\n  // An example of why Case 2 is required is comparing the following two Unicode code points:\n  //\n  // |-----------------------|------------|---------------------|-----------------|\n  // | Name                  | Code Point | UTF-8 Encoding      | UTF-16 Encoding |\n  // |-----------------------|------------|---------------------|-----------------|\n  // | Replacement Character | U+FFFD     | 0xEF 0xBF 0xBD      | 0xFFFD          |\n  // | Grinning Face         | U+1F600    | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00   |\n  // |-----------------------|------------|---------------------|-----------------|\n  //\n  // A lexicographical comparison of the UTF-8 encodings of these code points would order\n  // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n  // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n  // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n  // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n  // pair with those that do not.\n  const length = Math.min(left.length, right.length);\n  for (let i = 0; i < length; i++) {\n    const leftChar = left.charAt(i);\n    const rightChar = right.charAt(i);\n    if (leftChar !== rightChar) {\n      return isSurrogate(leftChar) === isSurrogate(rightChar)\n        ? primitiveComparator(leftChar, rightChar)\n        : isSurrogate(leftChar)\n        ? 1\n        : -1;\n    }\n  }\n\n  // Use the lengths of the strings to determine the overall comparison result since either the\n  // strings were equal or one is a prefix of the other.\n  return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n  debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n  const c = s.charCodeAt(0);\n  return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\n}\n\nexport interface Iterable<V> {\n  forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(\n  left: T[],\n  right: T[],\n  comparator: (l: T, r: T) => boolean\n): boolean {\n  if (left.length !== right.length) {\n    return false;\n  }\n  return left.every((value, index) => comparator(value, right[index]));\n}\n\n/**\n * Verifies equality for an optional value.\n */\nexport function isOptionalEqual<T>(\n  left: T | undefined,\n  right: T | undefined,\n  equalityTest: (left: T, right: T) => boolean\n): boolean {\n  if (left === undefined && right === undefined) {\n    return true;\n  }\n\n  if (left === undefined || right === undefined) {\n    return false;\n  }\n\n  return equalityTest(left, right);\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n  // Return the input string, with an additional NUL byte appended.\n  return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n  private segments: string[];\n  private offset: number;\n  private len: number;\n\n  constructor(segments: string[], offset?: number, length?: number) {\n    if (offset === undefined) {\n      offset = 0;\n    } else if (offset > segments.length) {\n      fail(0x027d, 'offset out of range', {\n        offset,\n        range: segments.length\n      });\n    }\n\n    if (length === undefined) {\n      length = segments.length - offset;\n    } else if (length > segments.length - offset) {\n      fail(0x06d2, 'length out of range', {\n        length,\n        range: segments.length - offset\n      });\n    }\n    this.segments = segments;\n    this.offset = offset;\n    this.len = length;\n  }\n\n  /**\n   * Abstract constructor method to construct an instance of B with the given\n   * parameters.\n   */\n  protected abstract construct(\n    segments: string[],\n    offset?: number,\n    length?: number\n  ): B;\n\n  /**\n   * Returns a String representation.\n   *\n   * Implementing classes are required to provide deterministic implementations as\n   * the String representation is used to obtain canonical Query IDs.\n   */\n  abstract toString(): string;\n\n  get length(): number {\n    return this.len;\n  }\n\n  isEqual(other: B): boolean {\n    return BasePath.comparator(this, other) === 0;\n  }\n\n  child(nameOrPath: string | B): B {\n    const segments = this.segments.slice(this.offset, this.limit());\n    if (nameOrPath instanceof BasePath) {\n      nameOrPath.forEach(segment => {\n        segments.push(segment);\n      });\n    } else {\n      segments.push(nameOrPath);\n    }\n    return this.construct(segments);\n  }\n\n  /** The index of one past the last segment of the path. */\n  private limit(): number {\n    return this.offset + this.length;\n  }\n\n  popFirst(size?: number): B {\n    size = size === undefined ? 1 : size;\n    debugAssert(\n      this.length >= size,\n      \"Can't call popFirst() with less segments\"\n    );\n    return this.construct(\n      this.segments,\n      this.offset + size,\n      this.length - size\n    );\n  }\n\n  popLast(): B {\n    debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n    return this.construct(this.segments, this.offset, this.length - 1);\n  }\n\n  firstSegment(): string {\n    debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n    return this.segments[this.offset];\n  }\n\n  lastSegment(): string {\n    debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n    return this.get(this.length - 1);\n  }\n\n  get(index: number): string {\n    debugAssert(index < this.length, 'Index out of range');\n    return this.segments[this.offset + index];\n  }\n\n  isEmpty(): boolean {\n    return this.length === 0;\n  }\n\n  isPrefixOf(other: this): boolean {\n    if (other.length < this.length) {\n      return false;\n    }\n\n    for (let i = 0; i < this.length; i++) {\n      if (this.get(i) !== other.get(i)) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  isImmediateParentOf(potentialChild: this): boolean {\n    if (this.length + 1 !== potentialChild.length) {\n      return false;\n    }\n\n    for (let i = 0; i < this.length; i++) {\n      if (this.get(i) !== potentialChild.get(i)) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  forEach(fn: (segment: string) => void): void {\n    for (let i = this.offset, end = this.limit(); i < end; i++) {\n      fn(this.segments[i]);\n    }\n  }\n\n  toArray(): string[] {\n    return this.segments.slice(this.offset, this.limit());\n  }\n\n  /**\n   * Compare 2 paths segment by segment, prioritizing numeric IDs\n   * (e.g., \"__id123__\") in numeric ascending order, followed by string\n   * segments in lexicographical order.\n   */\n  static comparator<T extends BasePath<T>>(\n    p1: BasePath<T>,\n    p2: BasePath<T>\n  ): number {\n    const len = Math.min(p1.length, p2.length);\n    for (let i = 0; i < len; i++) {\n      const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n      if (comparison !== 0) {\n        return comparison;\n      }\n    }\n    return primitiveComparator(p1.length, p2.length);\n  }\n\n  private static compareSegments(lhs: string, rhs: string): number {\n    const isLhsNumeric = BasePath.isNumericId(lhs);\n    const isRhsNumeric = BasePath.isNumericId(rhs);\n\n    if (isLhsNumeric && !isRhsNumeric) {\n      // Only lhs is numeric\n      return -1;\n    } else if (!isLhsNumeric && isRhsNumeric) {\n      // Only rhs is numeric\n      return 1;\n    } else if (isLhsNumeric && isRhsNumeric) {\n      // both numeric\n      return BasePath.extractNumericId(lhs).compare(\n        BasePath.extractNumericId(rhs)\n      );\n    } else {\n      // both non-numeric\n      return compareUtf8Strings(lhs, rhs);\n    }\n  }\n\n  // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n  private static isNumericId(segment: string): boolean {\n    return segment.startsWith('__id') && segment.endsWith('__');\n  }\n\n  private static extractNumericId(segment: string): Integer {\n    return Integer.fromString(segment.substring(4, segment.length - 2));\n  }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath<ResourcePath> {\n  protected construct(\n    segments: string[],\n    offset?: number,\n    length?: number\n  ): ResourcePath {\n    return new ResourcePath(segments, offset, length);\n  }\n\n  canonicalString(): string {\n    // NOTE: The client is ignorant of any path segments containing escape\n    // sequences (e.g. __id123__) and just passes them through raw (they exist\n    // for legacy reasons and should not be used frequently).\n\n    return this.toArray().join('/');\n  }\n\n  toString(): string {\n    return this.canonicalString();\n  }\n\n  /**\n   * Returns a string representation of this path\n   * where each path segment has been encoded with\n   * `encodeURIComponent`.\n   */\n  toUriEncodedString(): string {\n    return this.toArray().map(encodeURIComponent).join('/');\n  }\n\n  /**\n   * Creates a resource path from the given slash-delimited string. If multiple\n   * arguments are provided, all components are combined. Leading and trailing\n   * slashes from all components are ignored.\n   */\n  static fromString(...pathComponents: string[]): ResourcePath {\n    // NOTE: The client is ignorant of any path segments containing escape\n    // sequences (e.g. __id123__) and just passes them through raw (they exist\n    // for legacy reasons and should not be used frequently).\n\n    const segments: string[] = [];\n    for (const path of pathComponents) {\n      if (path.indexOf('//') >= 0) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid segment (${path}). Paths must not contain // in them.`\n        );\n      }\n      // Strip leading and trailing slashed.\n      segments.push(...path.split('/').filter(segment => segment.length > 0));\n    }\n\n    return new ResourcePath(segments);\n  }\n\n  static emptyPath(): ResourcePath {\n    return new ResourcePath([]);\n  }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath<FieldPath> {\n  protected construct(\n    segments: string[],\n    offset?: number,\n    length?: number\n  ): FieldPath {\n    return new FieldPath(segments, offset, length);\n  }\n\n  /**\n   * Returns true if the string could be used as a segment in a field path\n   * without escaping.\n   */\n  private static isValidIdentifier(segment: string): boolean {\n    return identifierRegExp.test(segment);\n  }\n\n  canonicalString(): string {\n    return this.toArray()\n      .map(str => {\n        str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n        if (!FieldPath.isValidIdentifier(str)) {\n          str = '`' + str + '`';\n        }\n        return str;\n      })\n      .join('.');\n  }\n\n  toString(): string {\n    return this.canonicalString();\n  }\n\n  /**\n   * Returns true if this field references the key of a document.\n   */\n  isKeyField(): boolean {\n    return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n  }\n\n  /**\n   * The field designating the key of a document.\n   */\n  static keyField(): FieldPath {\n    return new FieldPath([DOCUMENT_KEY_NAME]);\n  }\n\n  /**\n   * Parses a field string from the given server-formatted string.\n   *\n   * - Splitting the empty string is not allowed (for now at least).\n   * - Empty segments within the string (e.g. if there are two consecutive\n   *   separators) are not allowed.\n   *\n   * TODO(b/37244157): we should make this more strict. Right now, it allows\n   * non-identifier path components, even if they aren't escaped.\n   */\n  static fromServerFormat(path: string): FieldPath {\n    const segments: string[] = [];\n    let current = '';\n    let i = 0;\n\n    const addCurrentSegment = (): void => {\n      if (current.length === 0) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid field path (${path}). Paths must not be empty, begin ` +\n            `with '.', end with '.', or contain '..'`\n        );\n      }\n      segments.push(current);\n      current = '';\n    };\n\n    let inBackticks = false;\n\n    while (i < path.length) {\n      const c = path[i];\n      if (c === '\\\\') {\n        if (i + 1 === path.length) {\n          throw new FirestoreError(\n            Code.INVALID_ARGUMENT,\n            'Path has trailing escape character: ' + path\n          );\n        }\n        const next = path[i + 1];\n        if (!(next === '\\\\' || next === '.' || next === '`')) {\n          throw new FirestoreError(\n            Code.INVALID_ARGUMENT,\n            'Path has invalid escape sequence: ' + path\n          );\n        }\n        current += next;\n        i += 2;\n      } else if (c === '`') {\n        inBackticks = !inBackticks;\n        i++;\n      } else if (c === '.' && !inBackticks) {\n        addCurrentSegment();\n        i++;\n      } else {\n        current += c;\n        i++;\n      }\n    }\n    addCurrentSegment();\n\n    if (inBackticks) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Unterminated ` in path: ' + path\n      );\n    }\n\n    return new FieldPath(segments);\n  }\n\n  static emptyPath(): FieldPath {\n    return new FieldPath([]);\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n  constructor(readonly path: ResourcePath) {\n    debugAssert(\n      DocumentKey.isDocumentKey(path),\n      'Invalid DocumentKey with an odd number of segments: ' +\n        path.toArray().join('/')\n    );\n  }\n\n  static fromPath(path: string): DocumentKey {\n    return new DocumentKey(ResourcePath.fromString(path));\n  }\n\n  static fromName(name: string): DocumentKey {\n    return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n  }\n\n  static empty(): DocumentKey {\n    return new DocumentKey(ResourcePath.emptyPath());\n  }\n\n  get collectionGroup(): string {\n    debugAssert(\n      !this.path.isEmpty(),\n      'Cannot get collection group for empty key'\n    );\n    return this.path.popLast().lastSegment();\n  }\n\n  /** Returns true if the document is in the specified collectionId. */\n  hasCollectionId(collectionId: string): boolean {\n    return (\n      this.path.length >= 2 &&\n      this.path.get(this.path.length - 2) === collectionId\n    );\n  }\n\n  /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n  getCollectionGroup(): string {\n    debugAssert(\n      !this.path.isEmpty(),\n      'Cannot get collection group for empty key'\n    );\n    return this.path.get(this.path.length - 2);\n  }\n\n  /** Returns the fully qualified path to the parent collection. */\n  getCollectionPath(): ResourcePath {\n    return this.path.popLast();\n  }\n\n  isEqual(other: DocumentKey | null): boolean {\n    return (\n      other !== null && ResourcePath.comparator(this.path, other.path) === 0\n    );\n  }\n\n  toString(): string {\n    return this.path.toString();\n  }\n\n  static comparator(k1: DocumentKey, k2: DocumentKey): number {\n    return ResourcePath.comparator(k1.path, k2.path);\n  }\n\n  static isDocumentKey(path: ResourcePath): boolean {\n    return path.length % 2 === 0;\n  }\n\n  /**\n   * Creates and returns a new document key with the given segments.\n   *\n   * @param segments - The segments of the path to the document\n   * @returns A new instance of DocumentKey\n   */\n  static fromSegments(segments: string[]): DocumentKey {\n    return new DocumentKey(new ResourcePath(segments.slice()));\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '../lite-api/reference';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n  | 'undefined'\n  | 'object'\n  | 'function'\n  | 'boolean'\n  | 'number'\n  | 'string'\n  | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n  functionName: string,\n  argumentName: string,\n  argument?: string\n): asserts argument is string {\n  if (!argument) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n    );\n  }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n  optionName1: string,\n  argument1: boolean | undefined,\n  optionName2: string,\n  argument2: boolean | undefined\n): void {\n  if (argument1 === true && argument2 === true) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `${optionName1} and ${optionName2} cannot be used together.`\n    );\n  }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n  if (!DocumentKey.isDocumentKey(path)) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n    );\n  }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n  if (DocumentKey.isDocumentKey(path)) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n    );\n  }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): input is DocumentData {\n  return (\n    typeof input === 'object' &&\n    input !== null &&\n    (Object.getPrototypeOf(input) === Object.prototype ||\n      Object.getPrototypeOf(input) === null)\n  );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n  if (input === undefined) {\n    return 'undefined';\n  } else if (input === null) {\n    return 'null';\n  } else if (typeof input === 'string') {\n    if (input.length > 20) {\n      input = `${input.substring(0, 20)}...`;\n    }\n    return JSON.stringify(input);\n  } else if (typeof input === 'number' || typeof input === 'boolean') {\n    return '' + input;\n  } else if (typeof input === 'object') {\n    if (input instanceof Array) {\n      return 'an array';\n    } else {\n      const customObjectName = tryGetCustomObjectType(input!);\n      if (customObjectName) {\n        return `a custom ${customObjectName} object`;\n      } else {\n        return 'an object';\n      }\n    }\n  } else if (typeof input === 'function') {\n    return 'a function';\n  } else {\n    return fail(0x3029, 'Unknown wrong type', { type: typeof input });\n  }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n  if (input.constructor) {\n    return input.constructor.name;\n  }\n  return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if  `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast<T>(\n  obj: object,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor: { new (...args: any[]): T }\n): T | never {\n  if ('_delegate' in obj) {\n    // Unwrap Compat types\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    obj = (obj as any)._delegate;\n  }\n\n  if (!(obj instanceof constructor)) {\n    if (constructor.name === obj.constructor.name) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Type does not match the expected instance. Did you pass a ' +\n          `reference from a different Firestore SDK?`\n      );\n    } else {\n      const description = valueDescription(obj);\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Expected type '${constructor.name}', but it was: ${description}`\n      );\n    }\n  }\n  return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n  if (n <= 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Function ${functionName}() requires a positive number, but it was: ${n}.`\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n  /**\n   * The desired maximum timeout interval, in seconds, to complete a\n   * long-polling GET response. Valid values are between 5 and 30, inclusive.\n   * Floating point values are allowed and will be rounded to the nearest\n   * millisecond.\n   *\n   * By default, when long-polling is used the \"hanging GET\" request sent by\n   * the client times out after 30 seconds. To request a different timeout\n   * from the server, set this setting with the desired timeout.\n   *\n   * Changing the default timeout may be useful, for example, if the buffering\n   * proxy that necessitated enabling long-polling in the first place has a\n   * shorter timeout for hanging GET requests, in which case setting the\n   * long-polling timeout to a shorter value, such as 25 seconds, may fix\n   * prematurely-closed hanging GET requests.\n   * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n   */\n  timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n  options1: ExperimentalLongPollingOptions,\n  options2: ExperimentalLongPollingOptions\n): boolean {\n  return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n  options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n  const clone: ExperimentalLongPollingOptions = {};\n\n  if (options.timeoutSeconds !== undefined) {\n    clone.timeoutSeconds = options.timeoutSeconds;\n  }\n\n  return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n  const minResult = 0x10000000;\n  const maxResult = 0x90000000;\n  const resultRange = maxResult - minResult;\n  const resultOffset = Math.round(resultRange * Math.random());\n  return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @returns the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n  if (lastUniqueDebugId === null) {\n    lastUniqueDebugId = generateInitialUniqueDebugId();\n  } else {\n    lastUniqueDebugId++;\n  }\n  return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n  [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n  return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n  // Detect if the value is -0.0. Based on polyfill from\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n  return value === 0 && 1 / value === 1 / -0;\n}\n\nexport function isNumber(value: unknown): value is number {\n  return typeof value === 'number';\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n  return (\n    typeof value === 'number' &&\n    Number.isInteger(value) &&\n    !isNegativeZero(value) &&\n    value <= Number.MAX_SAFE_INTEGER &&\n    value >= Number.MIN_SAFE_INTEGER\n  );\n}\n\nexport function isString(value: unknown): value is string {\n  return typeof value === 'string';\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n  readonly localStorage: Storage;\n  readonly indexedDB: IDBFactory | null;\n  addEventListener(type: string, listener: EventListener): void;\n  removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n  readonly visibilityState: DocumentVisibilityState;\n  addEventListener(type: string, listener: EventListener): void;\n  removeEventListener(type: string, listener: EventListener): void;\n}\n\n/**\n * Utility type to create an type that only allows one\n * property of the Type param T to be set.\n *\n * @example\n * ```\n * type XorY = OneOf<{ x: unknown, y: unknown }>\n * let a = { x: \"foo\" }           // OK\n * let b = { y: \"foo\" }           // OK\n * let c = { a: \"foo\", y: \"foo\" } // Not OK\n * ```\n */\nexport type OneOf<T> = {\n  [K in keyof T]: Pick<T, K> & {\n    [P in Exclude<keyof T, K>]?: undefined;\n  };\n}[keyof T];\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n  DatabaseId,\n  DatabaseInfo,\n  DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\nRPC_NAME_URL_MAPPING['ExecutePipeline'] = 'executePipeline';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n  return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n  protected readonly databaseId: DatabaseId;\n  protected readonly baseUrl: string;\n  private readonly databasePath: string;\n  private readonly requestParams: string;\n\n  get shouldResourcePathBeIncludedInRequest(): boolean {\n    // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n    // where to run the query, and expect the `request` to NOT specify the \"path\".\n    return false;\n  }\n\n  constructor(protected readonly databaseInfo: DatabaseInfo) {\n    this.databaseId = databaseInfo.databaseId;\n    const proto = databaseInfo.ssl ? 'https' : 'http';\n    const projectId = encodeURIComponent(this.databaseId.projectId);\n    const databaseId = encodeURIComponent(this.databaseId.database);\n    this.baseUrl = proto + '://' + databaseInfo.host;\n    this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n    this.requestParams =\n      this.databaseId.database === DEFAULT_DATABASE_NAME\n        ? `project_id=${projectId}`\n        : `project_id=${projectId}&database_id=${databaseId}`;\n  }\n\n  invokeRPC<Req, Resp>(\n    rpcName: string,\n    path: ResourcePath,\n    req: Req,\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): Promise<Resp> {\n    const streamId = generateUniqueDebugId();\n    const url = this.makeUrl(rpcName, path.toUriEncodedString());\n    logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n    const headers: StringMap = {\n      'google-cloud-resource-prefix': this.databasePath,\n      'x-goog-request-params': this.requestParams\n    };\n    this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n    const { host } = new URL(url);\n    const forwardCredentials = isCloudWorkstation(host);\n    return this.performRPCRequest<Req, Resp>(\n      rpcName,\n      url,\n      headers,\n      req,\n      forwardCredentials\n    ).then(\n      response => {\n        logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n        return response;\n      },\n      (err: FirestoreError) => {\n        logWarn(\n          LOG_TAG,\n          `RPC '${rpcName}' ${streamId} failed with error: `,\n          err,\n          'url: ',\n          url,\n          'request:',\n          req\n        );\n        throw err;\n      }\n    );\n  }\n\n  invokeStreamingRPC<Req, Resp>(\n    rpcName: string,\n    path: ResourcePath,\n    request: Req,\n    authToken: Token | null,\n    appCheckToken: Token | null,\n    expectedResponseCount?: number\n  ): Promise<Resp[]> {\n    // The REST API automatically aggregates all of the streamed results, so we\n    // can just use the normal invoke() method.\n    return this.invokeRPC<Req, Resp[]>(\n      rpcName,\n      path,\n      request,\n      authToken,\n      appCheckToken\n    );\n  }\n\n  abstract openStream<Req, Resp>(\n    rpcName: string,\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): Stream<Req, Resp>;\n\n  /**\n   * Modifies the headers for a request, adding any authorization token if\n   * present and any additional headers for the request.\n   */\n  protected modifyHeadersForRequest(\n    headers: StringMap,\n    authToken: Token | null,\n    appCheckToken: Token | null\n  ): void {\n    headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n    // Content-Type: text/plain will avoid preflight requests which might\n    // mess with CORS and redirects by proxies. If we add custom headers\n    // we will need to change this code to potentially use the $httpOverwrite\n    // parameter supported by ESF to avoid triggering preflight requests.\n    headers['Content-Type'] = 'text/plain';\n\n    if (this.databaseInfo.appId) {\n      headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n    }\n\n    if (authToken) {\n      authToken.headers.forEach((value, key) => (headers[key] = value));\n    }\n    if (appCheckToken) {\n      appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n    }\n  }\n\n  /**\n   * Performs an RPC request using an implementation specific networking layer.\n   */\n  protected abstract performRPCRequest<Req, Resp>(\n    rpcName: string,\n    url: string,\n    headers: StringMap,\n    body: Req,\n    _forwardCredentials: boolean\n  ): Promise<Resp>;\n\n  protected makeUrl(rpcName: string, path: string): string {\n    const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n    debugAssert(\n      urlRpcName !== undefined,\n      'Unknown REST mapping for: ' + rpcName\n    );\n    let url = `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n    if (this.databaseInfo.apiKey) {\n      url = `${url}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`;\n    }\n    return url;\n  }\n\n  /**\n   * Closes and cleans up any resources associated with the connection. This\n   * implementation is a no-op because there are no resources associated\n   * with the RestConnection that need to be cleaned up.\n   */\n  terminate(): void {\n    // No-op\n  }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n  // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n  // In HTTP request builders, it's called with the protocol.\n  // If called with protocol prefix, it's a valid URL, so we extract the hostname\n  // If called without, we assume the string is the hostname.\n  try {\n    const host =\n      url.startsWith('http://') || url.startsWith('https://')\n        ? new URL(url).hostname\n        : url;\n    return host.endsWith('.cloudworkstations.dev');\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise<boolean> {\n  const result = await fetch(endpoint, {\n    credentials: 'include'\n  });\n  return result.ok;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n  OK = 0,\n  CANCELLED = 1,\n  UNKNOWN = 2,\n  INVALID_ARGUMENT = 3,\n  DEADLINE_EXCEEDED = 4,\n  NOT_FOUND = 5,\n  ALREADY_EXISTS = 6,\n  PERMISSION_DENIED = 7,\n  UNAUTHENTICATED = 16,\n  RESOURCE_EXHAUSTED = 8,\n  FAILED_PRECONDITION = 9,\n  ABORTED = 10,\n  OUT_OF_RANGE = 11,\n  UNIMPLEMENTED = 12,\n  INTERNAL = 13,\n  UNAVAILABLE = 14,\n  DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n  switch (code) {\n    case Code.OK:\n      return fail(0xfdaa, 'Treated status OK as error');\n    case Code.CANCELLED:\n    case Code.UNKNOWN:\n    case Code.DEADLINE_EXCEEDED:\n    case Code.RESOURCE_EXHAUSTED:\n    case Code.INTERNAL:\n    case Code.UNAVAILABLE:\n    // Unauthenticated means something went wrong with our token and we need\n    // to retry with new credentials which will happen automatically.\n    case Code.UNAUTHENTICATED:\n      return false;\n    case Code.INVALID_ARGUMENT:\n    case Code.NOT_FOUND:\n    case Code.ALREADY_EXISTS:\n    case Code.PERMISSION_DENIED:\n    case Code.FAILED_PRECONDITION:\n    // Aborted might be retried in some scenarios, but that is dependent on\n    // the context and should handled individually by the calling code.\n    // See https://cloud.google.com/apis/design/errors.\n    case Code.ABORTED:\n    case Code.OUT_OF_RANGE:\n    case Code.UNIMPLEMENTED:\n    case Code.DATA_LOSS:\n      return true;\n    default:\n      return fail(0x3c6b, 'Unknown status code', { code });\n  }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n  return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n *     there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n  // lookup by string\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const code: RpcCode = RpcCode[status as any] as any;\n  if (code === undefined) {\n    return undefined;\n  }\n\n  return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n *     is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n  if (code === undefined) {\n    // This shouldn't normally happen, but in certain error cases (like trying\n    // to send invalid proto messages) we may get an error with no GRPC code.\n    logError('GRPC error has no .code');\n    return Code.UNKNOWN;\n  }\n\n  switch (code) {\n    case RpcCode.OK:\n      return Code.OK;\n    case RpcCode.CANCELLED:\n      return Code.CANCELLED;\n    case RpcCode.UNKNOWN:\n      return Code.UNKNOWN;\n    case RpcCode.DEADLINE_EXCEEDED:\n      return Code.DEADLINE_EXCEEDED;\n    case RpcCode.RESOURCE_EXHAUSTED:\n      return Code.RESOURCE_EXHAUSTED;\n    case RpcCode.INTERNAL:\n      return Code.INTERNAL;\n    case RpcCode.UNAVAILABLE:\n      return Code.UNAVAILABLE;\n    case RpcCode.UNAUTHENTICATED:\n      return Code.UNAUTHENTICATED;\n    case RpcCode.INVALID_ARGUMENT:\n      return Code.INVALID_ARGUMENT;\n    case RpcCode.NOT_FOUND:\n      return Code.NOT_FOUND;\n    case RpcCode.ALREADY_EXISTS:\n      return Code.ALREADY_EXISTS;\n    case RpcCode.PERMISSION_DENIED:\n      return Code.PERMISSION_DENIED;\n    case RpcCode.FAILED_PRECONDITION:\n      return Code.FAILED_PRECONDITION;\n    case RpcCode.ABORTED:\n      return Code.ABORTED;\n    case RpcCode.OUT_OF_RANGE:\n      return Code.OUT_OF_RANGE;\n    case RpcCode.UNIMPLEMENTED:\n      return Code.UNIMPLEMENTED;\n    case RpcCode.DATA_LOSS:\n      return Code.DATA_LOSS;\n    default:\n      return fail(0x999b, 'Unknown status code', { code });\n  }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n  if (code === undefined) {\n    return RpcCode.OK;\n  }\n\n  switch (code) {\n    case Code.OK:\n      return RpcCode.OK;\n    case Code.CANCELLED:\n      return RpcCode.CANCELLED;\n    case Code.UNKNOWN:\n      return RpcCode.UNKNOWN;\n    case Code.DEADLINE_EXCEEDED:\n      return RpcCode.DEADLINE_EXCEEDED;\n    case Code.RESOURCE_EXHAUSTED:\n      return RpcCode.RESOURCE_EXHAUSTED;\n    case Code.INTERNAL:\n      return RpcCode.INTERNAL;\n    case Code.UNAVAILABLE:\n      return RpcCode.UNAVAILABLE;\n    case Code.UNAUTHENTICATED:\n      return RpcCode.UNAUTHENTICATED;\n    case Code.INVALID_ARGUMENT:\n      return RpcCode.INVALID_ARGUMENT;\n    case Code.NOT_FOUND:\n      return RpcCode.NOT_FOUND;\n    case Code.ALREADY_EXISTS:\n      return RpcCode.ALREADY_EXISTS;\n    case Code.PERMISSION_DENIED:\n      return RpcCode.PERMISSION_DENIED;\n    case Code.FAILED_PRECONDITION:\n      return RpcCode.FAILED_PRECONDITION;\n    case Code.ABORTED:\n      return RpcCode.ABORTED;\n    case Code.OUT_OF_RANGE:\n      return RpcCode.OUT_OF_RANGE;\n    case Code.UNIMPLEMENTED:\n      return RpcCode.UNIMPLEMENTED;\n    case Code.DATA_LOSS:\n      return RpcCode.DATA_LOSS;\n    default:\n      return fail(0x3019, 'Unknown status code', { code });\n  }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n *     Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n  if (status === undefined) {\n    logError('RPC_ERROR', 'HTTP error has no status');\n    return Code.UNKNOWN;\n  }\n\n  // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n  // status codes but the mapping is not bijective. In each case of ambiguity\n  // this function chooses a primary error.\n  //\n  // [1]\n  // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n  switch (status) {\n    case 200: // OK\n      return Code.OK;\n\n    case 400: // Bad Request\n      return Code.FAILED_PRECONDITION;\n    // Other possibilities based on the forward mapping\n    // return Code.INVALID_ARGUMENT;\n    // return Code.OUT_OF_RANGE;\n\n    case 401: // Unauthorized\n      return Code.UNAUTHENTICATED;\n\n    case 403: // Forbidden\n      return Code.PERMISSION_DENIED;\n\n    case 404: // Not Found\n      return Code.NOT_FOUND;\n\n    case 409: // Conflict\n      return Code.ABORTED;\n    // Other possibilities:\n    // return Code.ALREADY_EXISTS;\n\n    case 416: // Range Not Satisfiable\n      return Code.OUT_OF_RANGE;\n\n    case 429: // Too Many Requests\n      return Code.RESOURCE_EXHAUSTED;\n\n    case 499: // Client Closed Request\n      return Code.CANCELLED;\n\n    case 500: // Internal Server Error\n      return Code.UNKNOWN;\n    // Other possibilities:\n    // return Code.INTERNAL;\n    // return Code.DATA_LOSS;\n\n    case 501: // Unimplemented\n      return Code.UNIMPLEMENTED;\n\n    case 503: // Service Unavailable\n      return Code.UNAVAILABLE;\n\n    case 504: // Gateway Timeout\n      return Code.DEADLINE_EXCEEDED;\n\n    default:\n      if (status >= 200 && status < 300) {\n        return Code.OK;\n      }\n      if (status >= 400 && status < 500) {\n        return Code.FAILED_PRECONDITION;\n      }\n      if (status >= 500 && status < 600) {\n        return Code.INTERNAL;\n      }\n      return Code.UNKNOWN;\n  }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n *     Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n  const serverError = status.toLowerCase().replace(/_/g, '-');\n  return Object.values(Code).indexOf(serverError as Code) >= 0\n    ? (serverError as Code)\n    : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n  openStream<Req, Resp>(\n    rpcName: string,\n    token: Token | null\n  ): Stream<Req, Resp> {\n    throw new Error('Not supported by FetchConnection');\n  }\n\n  protected async performRPCRequest<Req, Resp>(\n    rpcName: string,\n    url: string,\n    headers: StringMap,\n    body: Req,\n    forwardCredentials: boolean\n  ): Promise<Resp> {\n    const requestJson = JSON.stringify(body);\n    let response: Response;\n\n    try {\n      const fetchArgs: RequestInit = {\n        method: 'POST',\n        headers,\n        body: requestJson\n      };\n      if (forwardCredentials) {\n        fetchArgs.credentials = 'include';\n      }\n      response = await fetch(url, fetchArgs);\n    } catch (e) {\n      const err = e as { status: number | undefined; statusText: string };\n      throw new FirestoreError(\n        mapCodeFromHttpStatus(err.status),\n        'Request failed with error: ' + err.statusText\n      );\n    }\n\n    if (!response.ok) {\n      let errorResponse = await response.json();\n      if (Array.isArray(errorResponse)) {\n        errorResponse = errorResponse[0];\n      }\n      const errorMessage = errorResponse?.error?.message;\n      throw new FirestoreError(\n        mapCodeFromHttpStatus(response.status),\n        `Request failed with error: ${errorMessage ?? response.statusText}`\n      );\n    }\n\n    return response.json();\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict<V> {\n  [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n  let count = 0;\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      count++;\n    }\n  }\n  return count;\n}\n\nexport function forEach<V>(\n  obj: Record<string, V> | undefined,\n  fn: (key: string, val: V) => void\n): void {\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      fn(key, obj[key]);\n    }\n  }\n}\n\nexport function mapToArray<V, R>(\n  obj: Dict<V>,\n  fn: (element: V, key: string, obj: Dict<V>) => R\n): R[] {\n  const result: R[] = [];\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      result.push(fn(obj[key], key, obj));\n    }\n  }\n  return result;\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n  debugAssert(\n    obj != null && typeof obj === 'object',\n    'isEmpty() expects object parameter.'\n  );\n  for (const key in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, key)) {\n      return false;\n    }\n  }\n  return true;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n  readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n  static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n  private constructor(private readonly binaryString: string) {}\n\n  static fromBase64String(base64: string): ByteString {\n    const binaryString = decodeBase64(base64);\n    return new ByteString(binaryString);\n  }\n\n  static fromUint8Array(array: Uint8Array): ByteString {\n    // TODO(indexing); Remove the copy of the byte string here as this method\n    // is frequently called during indexing.\n    const binaryString = binaryStringFromUint8Array(array);\n    return new ByteString(binaryString);\n  }\n\n  [Symbol.iterator](): Iterator<number> {\n    let i = 0;\n    return {\n      next: () => {\n        if (i < this.binaryString.length) {\n          return { value: this.binaryString.charCodeAt(i++), done: false };\n        } else {\n          return { value: undefined, done: true };\n        }\n      }\n    };\n  }\n\n  toBase64(): string {\n    return encodeBase64(this.binaryString);\n  }\n\n  toUint8Array(): Uint8Array {\n    return uint8ArrayFromBinaryString(this.binaryString);\n  }\n\n  approximateByteSize(): number {\n    return this.binaryString.length * 2;\n  }\n\n  compareTo(other: ByteString): number {\n    return primitiveComparator(this.binaryString, other.binaryString);\n  }\n\n  isEqual(other: ByteString): boolean {\n    return this.binaryString === other.binaryString;\n  }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n  let binaryString = '';\n  for (let i = 0; i < array.length; ++i) {\n    binaryString += String.fromCharCode(array[i]);\n  }\n  return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n  const buffer = new Uint8Array(binaryString.length);\n  for (let i = 0; i < binaryString.length; i++) {\n    buffer[i] = binaryString.charCodeAt(i);\n  }\n  return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n  try {\n    return atob(encoded);\n  } catch (e) {\n    // Check that `DOMException` is defined before using it to avoid\n    // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n    // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n    if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n      throw new Base64DecodeError('Invalid base64 string: ' + e);\n    } else {\n      throw e;\n    }\n  }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n  return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n  return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n  /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n  seconds: number;\n  nanos: number;\n} {\n  hardAssert(!!date, 0x986a, 'Cannot normalize null or undefined timestamp.');\n\n  // The json interface (for the browser) will return an iso timestamp string,\n  // while the proto js library (for node) will return a\n  // google.protobuf.Timestamp instance.\n  if (typeof date === 'string') {\n    // The date string can have higher precision (nanos) than the Date class\n    // (millis), so we do some custom parsing here.\n\n    // Parse the nanos right out of the string.\n    let nanos = 0;\n    const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n    hardAssert(!!fraction, 0xb5de, 'invalid timestamp', {\n      timestamp: date\n    });\n    if (fraction[1]) {\n      // Pad the fraction out to 9 digits (nanos).\n      let nanoStr = fraction[1];\n      nanoStr = (nanoStr + '000000000').substr(0, 9);\n      nanos = Number(nanoStr);\n    }\n\n    // Parse the date to get the seconds.\n    const parsedDate = new Date(date);\n    const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n    return { seconds, nanos };\n  } else {\n    // TODO(b/37282237): Use strings for Proto3 timestamps\n    // assert(!this.options.useProto3Json,\n    //   'The timestamp instance format requires Proto JS.');\n    const seconds = normalizeNumber(date.seconds);\n    const nanos = normalizeNumber(date.nanos);\n    return { seconds, nanos };\n  }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n  // TODO(bjornick): Handle int64 greater than 53 bits.\n  if (typeof value === 'number') {\n    return value;\n  } else if (typeof value === 'string') {\n    return Number(value);\n  } else {\n    return 0;\n  }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n  if (typeof blob === 'string') {\n    return ByteString.fromBase64String(blob);\n  } else {\n    return ByteString.fromUint8Array(blob);\n  }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n  | 'object'\n  | 'string'\n  | 'number'\n  | 'boolean'\n  | 'null'\n  | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType<T extends JsonTypeDesc> = T extends 'object'\n  ? object\n  : T extends 'string'\n  ? string\n  : T extends 'number'\n  ? number\n  : T extends 'boolean'\n  ? boolean\n  : T extends 'null'\n  ? null\n  : T extends 'undefined'\n  ? undefined\n  : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property<T extends JsonTypeDesc> {\n  value?: TSType<T>;\n  typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n  [key: string]: Property<JsonTypeDesc>;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json<T extends JsonSchema> = {\n  [K in keyof T]: Required<T[K]>['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property<T extends JsonTypeDesc>(\n  typeString: T,\n  optionalValue?: TSType<T>\n): Property<T> {\n  const result: Property<T> = {\n    typeString\n  };\n  if (optionalValue) {\n    result.value = optionalValue;\n  }\n  return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json - A JSON object to validate.\n * @param scheme - a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON<S extends JsonSchema>(\n  json: object,\n  schema: S\n): json is Json<S> {\n  if (!isPlainObject(json)) {\n    throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n  }\n  let error: string | undefined = undefined;\n  for (const key in schema) {\n    if (schema[key]) {\n      const typeString = schema[key].typeString;\n      const value: { value: unknown } | undefined =\n        'value' in schema[key] ? { value: schema[key].value } : undefined;\n      if (!(key in json)) {\n        error = `JSON missing required field: '${key}'`;\n        break;\n      }\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const fieldValue = (json as any)[key];\n      if (typeString && typeof fieldValue !== typeString) {\n        error = `JSON field '${key}' must be a ${typeString}.`;\n        break;\n      } else if (value !== undefined && fieldValue !== value.value) {\n        error = `Expected '${key}' field to equal '${value.value}'`;\n        break;\n      }\n    }\n  }\n  if (error) {\n    throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n  }\n  return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n  /**\n   * Creates a new timestamp with the current date, with millisecond precision.\n   *\n   * @returns a new timestamp representing the current date.\n   */\n  static now(): Timestamp {\n    return Timestamp.fromMillis(Date.now());\n  }\n\n  /**\n   * Creates a new timestamp from the given date.\n   *\n   * @param date - The date to initialize the `Timestamp` from.\n   * @returns A new `Timestamp` representing the same point in time as the given\n   *     date.\n   */\n  static fromDate(date: Date): Timestamp {\n    return Timestamp.fromMillis(date.getTime());\n  }\n\n  /**\n   * Creates a new timestamp from the given number of milliseconds.\n   *\n   * @param milliseconds - Number of milliseconds since Unix epoch\n   *     1970-01-01T00:00:00Z.\n   * @returns A new `Timestamp` representing the same point in time as the given\n   *     number of milliseconds.\n   */\n  static fromMillis(milliseconds: number): Timestamp {\n    const seconds = Math.floor(milliseconds / 1000);\n    const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n    return new Timestamp(seconds, nanos);\n  }\n\n  /**\n   * Creates a new timestamp.\n   *\n   * @param seconds - The number of seconds of UTC time since Unix epoch\n   *     1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n   *     9999-12-31T23:59:59Z inclusive.\n   * @param nanoseconds - The non-negative fractions of a second at nanosecond\n   *     resolution. Negative second values with fractions must still have\n   *     non-negative nanoseconds values that count forward in time. Must be\n   *     from 0 to 999,999,999 inclusive.\n   */\n  constructor(\n    /**\n     * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n     */\n    readonly seconds: number,\n    /**\n     * The fractions of a second at nanosecond resolution.*\n     */\n    readonly nanoseconds: number\n  ) {\n    if (nanoseconds < 0) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Timestamp nanoseconds out of range: ' + nanoseconds\n      );\n    }\n    if (nanoseconds >= 1e9) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Timestamp nanoseconds out of range: ' + nanoseconds\n      );\n    }\n    if (seconds < MIN_SECONDS) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Timestamp seconds out of range: ' + seconds\n      );\n    }\n    // This will break in the year 10,000.\n    if (seconds >= 253402300800) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Timestamp seconds out of range: ' + seconds\n      );\n    }\n  }\n\n  /**\n   * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n   * causes a loss of precision since `Date` objects only support millisecond\n   * precision.\n   *\n   * @returns JavaScript `Date` object representing the same point in time as\n   *     this `Timestamp`, with millisecond precision.\n   */\n  toDate(): Date {\n    return new Date(this.toMillis());\n  }\n\n  /**\n   * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n   * epoch). This operation causes a loss of precision.\n   *\n   * @returns The point in time corresponding to this timestamp, represented as\n   *     the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n   */\n  toMillis(): number {\n    return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n  }\n\n  _compareTo(other: Timestamp): number {\n    if (this.seconds === other.seconds) {\n      return primitiveComparator(this.nanoseconds, other.nanoseconds);\n    }\n    return primitiveComparator(this.seconds, other.seconds);\n  }\n\n  /**\n   * Returns true if this `Timestamp` is equal to the provided one.\n   *\n   * @param other - The `Timestamp` to compare against.\n   * @returns true if this `Timestamp` is equal to the provided one.\n   */\n  isEqual(other: Timestamp): boolean {\n    return (\n      other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n    );\n  }\n\n  /** Returns a textual representation of this `Timestamp`. */\n  toString(): string {\n    return (\n      'Timestamp(seconds=' +\n      this.seconds +\n      ', nanoseconds=' +\n      this.nanoseconds +\n      ')'\n    );\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n  static _jsonSchema = {\n    type: property('string', Timestamp._jsonSchemaVersion),\n    seconds: property('number'),\n    nanoseconds: property('number')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `Timestamp`.\n   */\n  toJSON(): { seconds: number; nanoseconds: number; type: string } {\n    return {\n      type: Timestamp._jsonSchemaVersion,\n      seconds: this.seconds,\n      nanoseconds: this.nanoseconds\n    };\n  }\n\n  /**\n   * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n   */\n  static fromJSON(json: object): Timestamp {\n    if (validateJSON(json, Timestamp._jsonSchema)) {\n      return new Timestamp(json.seconds, json.nanoseconds);\n    }\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Unexpected error creating Timestamp from JSON.'\n    );\n  }\n\n  /**\n   * Converts this object to a primitive string, which allows `Timestamp` objects\n   * to be compared using the `>`, `<=`, `>=` and `>` operators.\n   */\n  valueOf(): string {\n    // This method returns a string of the form <seconds>.<nanoseconds> where\n    // <seconds> is translated to have a non-negative value and both <seconds>\n    // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n    // Strings with this format then have a lexicographical ordering that matches\n    // the expected ordering. The <seconds> translation is done to avoid having\n    // a leading negative sign (i.e. a leading '-' character) in its string\n    // representation, which would affect its lexicographical ordering.\n    const adjustedSeconds = this.seconds - MIN_SECONDS;\n    // Note: Up to 12 decimal digits are required to represent all valid\n    // 'seconds' values.\n    const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n    const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n    return formattedSeconds + '.' + formattedNanoseconds;\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n  Value as ProtoValue,\n  MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n *   transform. They can only exist in the local view of a document. Therefore\n *   they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n *   evaluate to `null`. This behavior can be configured by passing custom\n *   FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n *   localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n  const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n  return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n  localWriteTime: Timestamp,\n  previousValue: ProtoValue | null\n): ProtoValue {\n  const mapValue: ProtoMapValue = {\n    fields: {\n      [TYPE_KEY]: {\n        stringValue: SERVER_TIMESTAMP_SENTINEL\n      },\n      [LOCAL_WRITE_TIME_KEY]: {\n        timestampValue: {\n          seconds: localWriteTime.seconds,\n          nanos: localWriteTime.nanoseconds\n        }\n      }\n    }\n  };\n\n  // We should avoid storing deeply nested server timestamp map values\n  // because we never use the intermediate \"previous values\".\n  // For example:\n  // previous: 42L, add: t1, result: t1 -> 42L\n  // previous: t1,  add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n  // previous: t2,  add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n  // `getPreviousValue` recursively traverses server timestamps to find the\n  // least recent Value.\n  if (previousValue && isServerTimestamp(previousValue)) {\n    previousValue = getPreviousValue(previousValue);\n  }\n  if (previousValue) {\n    mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n  }\n\n  return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n  const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n  if (isServerTimestamp(previousValue)) {\n    return getPreviousValue(previousValue);\n  }\n  return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n  const localWriteTime = normalizeTimestamp(\n    value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n  );\n  return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n  ArrayValue,\n  LatLng,\n  MapValue,\n  Timestamp,\n  Value as ProtoValue,\n  Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport {\n  arrayEquals,\n  compareUtf8Strings,\n  primitiveComparator\n} from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n  normalizeByteString,\n  normalizeNumber,\n  normalizeTimestamp\n} from './normalize';\nimport {\n  getLocalWriteTime,\n  getPreviousValue,\n  isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n  mapValue: {\n    fields: {\n      '__type__': { stringValue: MAX_VALUE_TYPE }\n    }\n  }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n  nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n  if ('nullValue' in value) {\n    return TypeOrder.NullValue;\n  } else if ('booleanValue' in value) {\n    return TypeOrder.BooleanValue;\n  } else if ('integerValue' in value || 'doubleValue' in value) {\n    return TypeOrder.NumberValue;\n  } else if ('timestampValue' in value) {\n    return TypeOrder.TimestampValue;\n  } else if ('stringValue' in value) {\n    return TypeOrder.StringValue;\n  } else if ('bytesValue' in value) {\n    return TypeOrder.BlobValue;\n  } else if ('referenceValue' in value) {\n    return TypeOrder.RefValue;\n  } else if ('geoPointValue' in value) {\n    return TypeOrder.GeoPointValue;\n  } else if ('arrayValue' in value) {\n    return TypeOrder.ArrayValue;\n  } else if ('mapValue' in value) {\n    if (isServerTimestamp(value)) {\n      return TypeOrder.ServerTimestampValue;\n    } else if (isMaxValue(value)) {\n      return TypeOrder.MaxValue;\n    } else if (isVectorValue(value)) {\n      return TypeOrder.VectorValue;\n    }\n    return TypeOrder.ObjectValue;\n  } else {\n    return fail(0x6e87, 'Invalid value type', { value });\n  }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n  if (left === right) {\n    return true;\n  }\n\n  const leftType = typeOrder(left);\n  const rightType = typeOrder(right);\n  if (leftType !== rightType) {\n    return false;\n  }\n\n  switch (leftType) {\n    case TypeOrder.NullValue:\n      return true;\n    case TypeOrder.BooleanValue:\n      return left.booleanValue === right.booleanValue;\n    case TypeOrder.ServerTimestampValue:\n      return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n    case TypeOrder.TimestampValue:\n      return timestampEquals(left, right);\n    case TypeOrder.StringValue:\n      return left.stringValue === right.stringValue;\n    case TypeOrder.BlobValue:\n      return blobEquals(left, right);\n    case TypeOrder.RefValue:\n      return left.referenceValue === right.referenceValue;\n    case TypeOrder.GeoPointValue:\n      return geoPointEquals(left, right);\n    case TypeOrder.NumberValue:\n      return numberEquals(left, right);\n    case TypeOrder.ArrayValue:\n      return arrayEquals(\n        left.arrayValue!.values || [],\n        right.arrayValue!.values || [],\n        valueEquals\n      );\n    case TypeOrder.VectorValue:\n    case TypeOrder.ObjectValue:\n      return objectEquals(left, right);\n    case TypeOrder.MaxValue:\n      return true;\n    default:\n      return fail(0xcbf8, 'Unexpected value type', { left });\n  }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n  if (\n    typeof left.timestampValue === 'string' &&\n    typeof right.timestampValue === 'string' &&\n    left.timestampValue.length === right.timestampValue.length\n  ) {\n    // Use string equality for ISO 8601 timestamps\n    return left.timestampValue === right.timestampValue;\n  }\n\n  const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n  const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n  return (\n    leftTimestamp.seconds === rightTimestamp.seconds &&\n    leftTimestamp.nanos === rightTimestamp.nanos\n  );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n  return (\n    normalizeNumber(left.geoPointValue!.latitude) ===\n      normalizeNumber(right.geoPointValue!.latitude) &&\n    normalizeNumber(left.geoPointValue!.longitude) ===\n      normalizeNumber(right.geoPointValue!.longitude)\n  );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n  return normalizeByteString(left.bytesValue!).isEqual(\n    normalizeByteString(right.bytesValue!)\n  );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n  if ('integerValue' in left && 'integerValue' in right) {\n    return (\n      normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n    );\n  } else if ('doubleValue' in left && 'doubleValue' in right) {\n    const n1 = normalizeNumber(left.doubleValue!);\n    const n2 = normalizeNumber(right.doubleValue!);\n\n    if (n1 === n2) {\n      return isNegativeZero(n1) === isNegativeZero(n2);\n    } else {\n      return isNaN(n1) && isNaN(n2);\n    }\n  }\n\n  return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n  const leftMap = left.mapValue!.fields || {};\n  const rightMap = right.mapValue!.fields || {};\n\n  if (objectSize(leftMap) !== objectSize(rightMap)) {\n    return false;\n  }\n\n  for (const key in leftMap) {\n    if (leftMap.hasOwnProperty(key)) {\n      if (\n        rightMap[key] === undefined ||\n        !valueEquals(leftMap[key], rightMap[key])\n      ) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n  haystack: ArrayValue,\n  needle: Value\n): boolean {\n  return (\n    (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n  );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n  if (left === right) {\n    return 0;\n  }\n\n  const leftType = typeOrder(left);\n  const rightType = typeOrder(right);\n\n  if (leftType !== rightType) {\n    return primitiveComparator(leftType, rightType);\n  }\n\n  switch (leftType) {\n    case TypeOrder.NullValue:\n    case TypeOrder.MaxValue:\n      return 0;\n    case TypeOrder.BooleanValue:\n      return primitiveComparator(left.booleanValue!, right.booleanValue!);\n    case TypeOrder.NumberValue:\n      return compareNumbers(left, right);\n    case TypeOrder.TimestampValue:\n      return compareTimestamps(left.timestampValue!, right.timestampValue!);\n    case TypeOrder.ServerTimestampValue:\n      return compareTimestamps(\n        getLocalWriteTime(left),\n        getLocalWriteTime(right)\n      );\n    case TypeOrder.StringValue:\n      return compareUtf8Strings(left.stringValue!, right.stringValue!);\n    case TypeOrder.BlobValue:\n      return compareBlobs(left.bytesValue!, right.bytesValue!);\n    case TypeOrder.RefValue:\n      return compareReferences(left.referenceValue!, right.referenceValue!);\n    case TypeOrder.GeoPointValue:\n      return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n    case TypeOrder.ArrayValue:\n      return compareArrays(left.arrayValue!, right.arrayValue!);\n    case TypeOrder.VectorValue:\n      return compareVectors(left.mapValue!, right.mapValue!);\n    case TypeOrder.ObjectValue:\n      return compareMaps(left.mapValue!, right.mapValue!);\n    default:\n      throw fail(0x5ae0, 'Invalid value type', { leftType });\n  }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n  const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n  const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n  if (leftNumber < rightNumber) {\n    return -1;\n  } else if (leftNumber > rightNumber) {\n    return 1;\n  } else if (leftNumber === rightNumber) {\n    return 0;\n  } else {\n    // one or both are NaN.\n    if (isNaN(leftNumber)) {\n      return isNaN(rightNumber) ? 0 : -1;\n    } else {\n      return 1;\n    }\n  }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n  if (\n    typeof left === 'string' &&\n    typeof right === 'string' &&\n    left.length === right.length\n  ) {\n    return primitiveComparator(left, right);\n  }\n\n  const leftTimestamp = normalizeTimestamp(left);\n  const rightTimestamp = normalizeTimestamp(right);\n\n  const comparison = primitiveComparator(\n    leftTimestamp.seconds,\n    rightTimestamp.seconds\n  );\n  if (comparison !== 0) {\n    return comparison;\n  }\n  return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n  const leftSegments = leftPath.split('/');\n  const rightSegments = rightPath.split('/');\n  for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n    const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n    if (comparison !== 0) {\n      return comparison;\n    }\n  }\n  return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n  const comparison = primitiveComparator(\n    normalizeNumber(left.latitude),\n    normalizeNumber(right.latitude)\n  );\n  if (comparison !== 0) {\n    return comparison;\n  }\n  return primitiveComparator(\n    normalizeNumber(left.longitude),\n    normalizeNumber(right.longitude)\n  );\n}\n\nfunction compareBlobs(\n  left: string | Uint8Array,\n  right: string | Uint8Array\n): number {\n  const leftBytes = normalizeByteString(left);\n  const rightBytes = normalizeByteString(right);\n  return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n  const leftArray = left.values || [];\n  const rightArray = right.values || [];\n\n  for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n    const compare = valueCompare(leftArray[i], rightArray[i]);\n    if (compare) {\n      return compare;\n    }\n  }\n  return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n  const leftMap = left.fields || {};\n  const rightMap = right.fields || {};\n\n  // The vector is a map, but only vector value is compared.\n  const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n  const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n  const lengthCompare = primitiveComparator(\n    leftArrayValue?.values?.length || 0,\n    rightArrayValue?.values?.length || 0\n  );\n  if (lengthCompare !== 0) {\n    return lengthCompare;\n  }\n\n  return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n  if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n    return 0;\n  } else if (left === MAX_VALUE.mapValue) {\n    return 1;\n  } else if (right === MAX_VALUE.mapValue) {\n    return -1;\n  }\n\n  const leftMap = left.fields || {};\n  const leftKeys = Object.keys(leftMap);\n  const rightMap = right.fields || {};\n  const rightKeys = Object.keys(rightMap);\n\n  // Even though MapValues are likely sorted correctly based on their insertion\n  // order (e.g. when received from the backend), local modifications can bring\n  // elements out of order. We need to re-sort the elements to ensure that\n  // canonical IDs are independent of insertion order.\n  leftKeys.sort();\n  rightKeys.sort();\n\n  for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n    const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]);\n    if (keyCompare !== 0) {\n      return keyCompare;\n    }\n    const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n    if (compare !== 0) {\n      return compare;\n    }\n  }\n\n  return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n  return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n  if ('nullValue' in value) {\n    return 'null';\n  } else if ('booleanValue' in value) {\n    return '' + value.booleanValue!;\n  } else if ('integerValue' in value) {\n    return '' + value.integerValue!;\n  } else if ('doubleValue' in value) {\n    return '' + value.doubleValue!;\n  } else if ('timestampValue' in value) {\n    return canonifyTimestamp(value.timestampValue!);\n  } else if ('stringValue' in value) {\n    return value.stringValue!;\n  } else if ('bytesValue' in value) {\n    return canonifyByteString(value.bytesValue!);\n  } else if ('referenceValue' in value) {\n    return canonifyReference(value.referenceValue!);\n  } else if ('geoPointValue' in value) {\n    return canonifyGeoPoint(value.geoPointValue!);\n  } else if ('arrayValue' in value) {\n    return canonifyArray(value.arrayValue!);\n  } else if ('mapValue' in value) {\n    return canonifyMap(value.mapValue!);\n  } else {\n    return fail(0xee4d, 'Invalid value type', { value });\n  }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n  return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n  const normalizedTimestamp = normalizeTimestamp(timestamp);\n  return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n  return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n  return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n  // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n  // matching canonical IDs for identical maps, we need to sort the keys.\n  const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n  let result = '{';\n  let first = true;\n  for (const key of sortedKeys) {\n    if (!first) {\n      result += ',';\n    } else {\n      first = false;\n    }\n    result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n  }\n  return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n  let result = '[';\n  let first = true;\n  for (const value of arrayValue.values || []) {\n    if (!first) {\n      result += ',';\n    } else {\n      first = false;\n    }\n    result += canonifyValue(value);\n  }\n  return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n  switch (typeOrder(value)) {\n    case TypeOrder.NullValue:\n      return 4;\n    case TypeOrder.BooleanValue:\n      return 4;\n    case TypeOrder.NumberValue:\n      return 8;\n    case TypeOrder.TimestampValue:\n      // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n      return 16;\n    case TypeOrder.ServerTimestampValue:\n      const previousValue = getPreviousValue(value);\n      return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n    case TypeOrder.StringValue:\n      // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n      // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n      // integer values\"\n      return value.stringValue!.length * 2;\n    case TypeOrder.BlobValue:\n      return normalizeByteString(value.bytesValue!).approximateByteSize();\n    case TypeOrder.RefValue:\n      return value.referenceValue!.length;\n    case TypeOrder.GeoPointValue:\n      // GeoPoints are made up of two distinct numbers (latitude + longitude)\n      return 16;\n    case TypeOrder.ArrayValue:\n      return estimateArrayByteSize(value.arrayValue!);\n    case TypeOrder.VectorValue:\n    case TypeOrder.ObjectValue:\n      return estimateMapByteSize(value.mapValue!);\n    default:\n      throw fail(0x34ae, 'Invalid value type', { value });\n  }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n  let size = 0;\n  forEach(mapValue.fields, (key, val) => {\n    size += key.length + estimateByteSize(val);\n  });\n  return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n  return (arrayValue.values || []).reduce(\n    (previousSize, value) => previousSize + estimateByteSize(value),\n    0\n  );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n  return {\n    referenceValue: `projects/${databaseId.projectId}/databases/${\n      databaseId.database\n    }/documents/${key.path.canonicalString()}`\n  };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n  value?: Value | null\n): value is { integerValue: string | number } {\n  return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n  value?: Value | null\n): value is { doubleValue: string | number } {\n  return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n  return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n  value?: Value | null\n): value is { arrayValue: ArrayValue } {\n  return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n  value?: Value | null\n): value is { referenceValue: string } {\n  return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n  value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n  return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n  value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n  return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n  value?: Value | null\n): value is { mapValue: MapValue } {\n  return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n  const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n  return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n  if (source.geoPointValue) {\n    return { geoPointValue: { ...source.geoPointValue } };\n  } else if (\n    source.timestampValue &&\n    typeof source.timestampValue === 'object'\n  ) {\n    return { timestampValue: { ...source.timestampValue } };\n  } else if (source.mapValue) {\n    const target: Value = { mapValue: { fields: {} } };\n    forEach(\n      source.mapValue.fields,\n      (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n    );\n    return target;\n  } else if (source.arrayValue) {\n    const target: Value = { arrayValue: { values: [] } };\n    for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n      target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n    }\n    return target;\n  } else {\n    return { ...source };\n  }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n  return (\n    (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n    MAX_VALUE_TYPE\n  );\n}\n\nexport const MIN_VECTOR_VALUE = {\n  mapValue: {\n    fields: {\n      [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n      [VECTOR_MAP_VECTORS_KEY]: {\n        arrayValue: {}\n      }\n    }\n  }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n  if ('nullValue' in value) {\n    return MIN_VALUE;\n  } else if ('booleanValue' in value) {\n    return { booleanValue: false };\n  } else if ('integerValue' in value || 'doubleValue' in value) {\n    return { doubleValue: NaN };\n  } else if ('timestampValue' in value) {\n    return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n  } else if ('stringValue' in value) {\n    return { stringValue: '' };\n  } else if ('bytesValue' in value) {\n    return { bytesValue: '' };\n  } else if ('referenceValue' in value) {\n    return refValue(DatabaseId.empty(), DocumentKey.empty());\n  } else if ('geoPointValue' in value) {\n    return { geoPointValue: { latitude: -90, longitude: -180 } };\n  } else if ('arrayValue' in value) {\n    return { arrayValue: {} };\n  } else if ('mapValue' in value) {\n    if (isVectorValue(value)) {\n      return MIN_VECTOR_VALUE;\n    }\n    return { mapValue: {} };\n  } else {\n    return fail(0x8c66, 'Invalid value type', { value });\n  }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n  if ('nullValue' in value) {\n    return { booleanValue: false };\n  } else if ('booleanValue' in value) {\n    return { doubleValue: NaN };\n  } else if ('integerValue' in value || 'doubleValue' in value) {\n    return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n  } else if ('timestampValue' in value) {\n    return { stringValue: '' };\n  } else if ('stringValue' in value) {\n    return { bytesValue: '' };\n  } else if ('bytesValue' in value) {\n    return refValue(DatabaseId.empty(), DocumentKey.empty());\n  } else if ('referenceValue' in value) {\n    return { geoPointValue: { latitude: -90, longitude: -180 } };\n  } else if ('geoPointValue' in value) {\n    return { arrayValue: {} };\n  } else if ('arrayValue' in value) {\n    return MIN_VECTOR_VALUE;\n  } else if ('mapValue' in value) {\n    if (isVectorValue(value)) {\n      return { mapValue: {} };\n    }\n    return MAX_VALUE;\n  } else {\n    return fail(0xf207, 'Invalid value type', { value });\n  }\n}\n\nexport function lowerBoundCompare(\n  left: { value: Value; inclusive: boolean },\n  right: { value: Value; inclusive: boolean }\n): number {\n  const cmp = valueCompare(left.value, right.value);\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  if (left.inclusive && !right.inclusive) {\n    return -1;\n  } else if (!left.inclusive && right.inclusive) {\n    return 1;\n  }\n\n  return 0;\n}\n\nexport function upperBoundCompare(\n  left: { value: Value; inclusive: boolean },\n  right: { value: Value; inclusive: boolean }\n): number {\n  const cmp = valueCompare(left.value, right.value);\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  if (left.inclusive && !right.inclusive) {\n    return 1;\n  } else if (!left.inclusive && right.inclusive) {\n    return -1;\n  }\n\n  return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n  arrayValueContains,\n  canonicalId,\n  isArray,\n  isReferenceValue,\n  typeOrder,\n  valueCompare,\n  valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n  LESS_THAN = '<',\n  LESS_THAN_OR_EQUAL = '<=',\n  EQUAL = '==',\n  NOT_EQUAL = '!=',\n  GREATER_THAN = '>',\n  GREATER_THAN_OR_EQUAL = '>=',\n  ARRAY_CONTAINS = 'array-contains',\n  IN = 'in',\n  NOT_IN = 'not-in',\n  ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n  OR = 'or',\n  AND = 'and'\n}\n\nexport abstract class Filter {\n  abstract matches(doc: Document): boolean;\n\n  abstract getFlattenedFilters(): readonly FieldFilter[];\n\n  abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n  protected constructor(\n    public readonly field: FieldPath,\n    public readonly op: Operator,\n    public readonly value: ProtoValue\n  ) {\n    super();\n  }\n\n  /**\n   * Creates a filter based on the provided arguments.\n   */\n  static create(\n    field: FieldPath,\n    op: Operator,\n    value: ProtoValue\n  ): FieldFilter {\n    if (field.isKeyField()) {\n      if (op === Operator.IN || op === Operator.NOT_IN) {\n        return this.createKeyFieldInFilter(field, op, value);\n      } else {\n        debugAssert(\n          isReferenceValue(value),\n          'Comparing on key, but filter value not a RefValue'\n        );\n        debugAssert(\n          op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n          `'${op.toString()}' queries don't make sense on document keys.`\n        );\n        return new KeyFieldFilter(field, op, value);\n      }\n    } else if (op === Operator.ARRAY_CONTAINS) {\n      return new ArrayContainsFilter(field, value);\n    } else if (op === Operator.IN) {\n      debugAssert(\n        isArray(value),\n        'IN filter has invalid value: ' + value.toString()\n      );\n      return new InFilter(field, value);\n    } else if (op === Operator.NOT_IN) {\n      debugAssert(\n        isArray(value),\n        'NOT_IN filter has invalid value: ' + value.toString()\n      );\n      return new NotInFilter(field, value);\n    } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n      debugAssert(\n        isArray(value),\n        'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n      );\n      return new ArrayContainsAnyFilter(field, value);\n    } else {\n      return new FieldFilter(field, op, value);\n    }\n  }\n\n  private static createKeyFieldInFilter(\n    field: FieldPath,\n    op: Operator.IN | Operator.NOT_IN,\n    value: ProtoValue\n  ): FieldFilter {\n    debugAssert(\n      isArray(value),\n      `Comparing on key with ${op.toString()}` +\n        ', but filter value not an ArrayValue'\n    );\n    debugAssert(\n      (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n      `Comparing on key with ${op.toString()}` +\n        ', but an array value was not a RefValue'\n    );\n\n    return op === Operator.IN\n      ? new KeyFieldInFilter(field, value)\n      : new KeyFieldNotInFilter(field, value);\n  }\n\n  matches(doc: Document): boolean {\n    const other = doc.data.field(this.field);\n    // Types do not have to match in NOT_EQUAL filters.\n    if (this.op === Operator.NOT_EQUAL) {\n      return (\n        other !== null &&\n        other.nullValue === undefined &&\n        this.matchesComparison(valueCompare(other!, this.value))\n      );\n    }\n\n    // Only compare types with matching backend order (such as double and int).\n    return (\n      other !== null &&\n      typeOrder(this.value) === typeOrder(other) &&\n      this.matchesComparison(valueCompare(other, this.value))\n    );\n  }\n\n  protected matchesComparison(comparison: number): boolean {\n    switch (this.op) {\n      case Operator.LESS_THAN:\n        return comparison < 0;\n      case Operator.LESS_THAN_OR_EQUAL:\n        return comparison <= 0;\n      case Operator.EQUAL:\n        return comparison === 0;\n      case Operator.NOT_EQUAL:\n        return comparison !== 0;\n      case Operator.GREATER_THAN:\n        return comparison > 0;\n      case Operator.GREATER_THAN_OR_EQUAL:\n        return comparison >= 0;\n      default:\n        return fail(0xb8a2, 'Unknown FieldFilter operator', {\n          operator: this.op\n        });\n    }\n  }\n\n  isInequality(): boolean {\n    return (\n      [\n        Operator.LESS_THAN,\n        Operator.LESS_THAN_OR_EQUAL,\n        Operator.GREATER_THAN,\n        Operator.GREATER_THAN_OR_EQUAL,\n        Operator.NOT_EQUAL,\n        Operator.NOT_IN\n      ].indexOf(this.op) >= 0\n    );\n  }\n\n  getFlattenedFilters(): readonly FieldFilter[] {\n    return [this];\n  }\n\n  getFilters(): Filter[] {\n    return [this];\n  }\n}\n\nexport class CompositeFilter extends Filter {\n  private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n  protected constructor(\n    public readonly filters: readonly Filter[],\n    public readonly op: CompositeOperator\n  ) {\n    super();\n  }\n\n  /**\n   * Creates a filter based on the provided arguments.\n   */\n  static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n    return new CompositeFilter(filters, op);\n  }\n\n  matches(doc: Document): boolean {\n    if (compositeFilterIsConjunction(this)) {\n      // For conjunctions, all filters must match, so return false if any filter doesn't match.\n      return this.filters.find(filter => !filter.matches(doc)) === undefined;\n    } else {\n      // For disjunctions, at least one filter should match.\n      return this.filters.find(filter => filter.matches(doc)) !== undefined;\n    }\n  }\n\n  getFlattenedFilters(): readonly FieldFilter[] {\n    if (this.memoizedFlattenedFilters !== null) {\n      return this.memoizedFlattenedFilters;\n    }\n\n    this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n      return result.concat(subfilter.getFlattenedFilters());\n    }, [] as FieldFilter[]);\n\n    return this.memoizedFlattenedFilters;\n  }\n\n  // Returns a mutable copy of `this.filters`\n  getFilters(): Filter[] {\n    return Object.assign([], this.filters);\n  }\n}\n\nexport function compositeFilterIsConjunction(\n  compositeFilter: CompositeFilter\n): boolean {\n  return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n  compositeFilter: CompositeFilter\n): boolean {\n  return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n  compositeFilter: CompositeFilter\n): boolean {\n  return (\n    compositeFilterIsFlat(compositeFilter) &&\n    compositeFilterIsConjunction(compositeFilter)\n  );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n  compositeFilter: CompositeFilter\n): boolean {\n  for (const filter of compositeFilter.filters) {\n    if (filter instanceof CompositeFilter) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n  debugAssert(\n    filter instanceof FieldFilter || filter instanceof CompositeFilter,\n    'canonifyFilter() only supports FieldFilters and CompositeFilters'\n  );\n\n  if (filter instanceof FieldFilter) {\n    // TODO(b/29183165): Technically, this won't be unique if two values have\n    // the same description, such as the int 3 and the string \"3\". So we should\n    // add the types in here somehow, too.\n    return (\n      filter.field.canonicalString() +\n      filter.op.toString() +\n      canonicalId(filter.value)\n    );\n  } else if (compositeFilterIsFlatConjunction(filter)) {\n    // Older SDK versions use an implicit AND operation between their filters.\n    // In the new SDK versions, the developer may use an explicit AND filter.\n    // To stay consistent with the old usages, we add a special case to ensure\n    // the canonical ID for these two are the same. For example:\n    // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n    // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n    return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n  } else {\n    // filter instanceof CompositeFilter\n    const canonicalIdsString = filter.filters\n      .map(filter => canonifyFilter(filter))\n      .join(',');\n    return `${filter.op}(${canonicalIdsString})`;\n  }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n  if (f1 instanceof FieldFilter) {\n    return fieldFilterEquals(f1, f2);\n  } else if (f1 instanceof CompositeFilter) {\n    return compositeFilterEquals(f1, f2);\n  } else {\n    fail(0x4bef, 'Only FieldFilters and CompositeFilters can be compared');\n  }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n  return (\n    f2 instanceof FieldFilter &&\n    f1.op === f2.op &&\n    f1.field.isEqual(f2.field) &&\n    valueEquals(f1.value, f2.value)\n  );\n}\n\nexport function compositeFilterEquals(\n  f1: CompositeFilter,\n  f2: Filter\n): boolean {\n  if (\n    f2 instanceof CompositeFilter &&\n    f1.op === f2.op &&\n    f1.filters.length === f2.filters.length\n  ) {\n    const subFiltersMatch: boolean = f1.filters.reduce(\n      (result: boolean, f1Filter: Filter, index: number): boolean =>\n        result && filterEquals(f1Filter, f2.filters[index]),\n      true\n    );\n\n    return subFiltersMatch;\n  }\n\n  return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n  compositeFilter: CompositeFilter,\n  otherFilters: Filter[]\n): CompositeFilter {\n  const mergedFilters = compositeFilter.filters.concat(otherFilters);\n  return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n  debugAssert(\n    filter instanceof FieldFilter || filter instanceof CompositeFilter,\n    'stringifyFilter() only supports FieldFilters and CompositeFilters'\n  );\n  if (filter instanceof FieldFilter) {\n    return stringifyFieldFilter(filter);\n  } else if (filter instanceof CompositeFilter) {\n    return stringifyCompositeFilter(filter);\n  } else {\n    return 'Filter';\n  }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n  return (\n    filter.op.toString() +\n    ` {` +\n    filter.getFilters().map(stringifyFilter).join(' ,') +\n    '}'\n  );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n  return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n    filter.value\n  )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n  private readonly key: DocumentKey;\n\n  constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n    super(field, op, value);\n    debugAssert(\n      isReferenceValue(value),\n      'KeyFieldFilter expects a ReferenceValue'\n    );\n    this.key = DocumentKey.fromName(value.referenceValue);\n  }\n\n  matches(doc: Document): boolean {\n    const comparison = DocumentKey.comparator(doc.key, this.key);\n    return this.matchesComparison(comparison);\n  }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n  private readonly keys: DocumentKey[];\n\n  constructor(field: FieldPath, value: ProtoValue) {\n    super(field, Operator.IN, value);\n    this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n  }\n\n  matches(doc: Document): boolean {\n    return this.keys.some(key => key.isEqual(doc.key));\n  }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n  private readonly keys: DocumentKey[];\n\n  constructor(field: FieldPath, value: ProtoValue) {\n    super(field, Operator.NOT_IN, value);\n    this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n  }\n\n  matches(doc: Document): boolean {\n    return !this.keys.some(key => key.isEqual(doc.key));\n  }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n  op: Operator.IN | Operator.NOT_IN,\n  value: ProtoValue\n): DocumentKey[] {\n  debugAssert(\n    isArray(value),\n    'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n  );\n  return (value.arrayValue?.values || []).map(v => {\n    debugAssert(\n      isReferenceValue(v),\n      `Comparing on key with ${op.toString()}, but an array value was not ` +\n        `a ReferenceValue`\n    );\n    return DocumentKey.fromName(v.referenceValue);\n  });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n  constructor(field: FieldPath, value: ProtoValue) {\n    super(field, Operator.ARRAY_CONTAINS, value);\n  }\n\n  matches(doc: Document): boolean {\n    const other = doc.data.field(this.field);\n    return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n  }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n  constructor(field: FieldPath, value: ProtoValue) {\n    super(field, Operator.IN, value);\n    debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n  }\n\n  matches(doc: Document): boolean {\n    const other = doc.data.field(this.field);\n    return other !== null && arrayValueContains(this.value.arrayValue!, other);\n  }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n  constructor(field: FieldPath, value: ProtoValue) {\n    super(field, Operator.NOT_IN, value);\n    debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n  }\n\n  matches(doc: Document): boolean {\n    if (\n      arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n    ) {\n      return false;\n    }\n    const other = doc.data.field(this.field);\n    return (\n      other !== null &&\n      other.nullValue === undefined &&\n      !arrayValueContains(this.value.arrayValue!, other)\n    );\n  }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n  constructor(field: FieldPath, value: ProtoValue) {\n    super(field, Operator.ARRAY_CONTAINS_ANY, value);\n    debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n  }\n\n  matches(doc: Document): boolean {\n    const other = doc.data.field(this.field);\n    if (!isArray(other) || !other.arrayValue.values) {\n      return false;\n    }\n    return other.arrayValue.values.some(val =>\n      arrayValueContains(this.value.arrayValue!, val)\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n  ASCENDING = 'asc',\n  DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n  constructor(\n    readonly field: FieldPath,\n    readonly dir: Direction = Direction.ASCENDING\n  ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n  // TODO(b/29183165): Make this collision robust.\n  return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n  return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n  return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n  static fromTimestamp(value: Timestamp): SnapshotVersion {\n    return new SnapshotVersion(value);\n  }\n\n  static min(): SnapshotVersion {\n    return new SnapshotVersion(new Timestamp(0, 0));\n  }\n\n  static max(): SnapshotVersion {\n    return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n  }\n\n  private constructor(private timestamp: Timestamp) {}\n\n  compareTo(other: SnapshotVersion): number {\n    return this.timestamp._compareTo(other.timestamp);\n  }\n\n  isEqual(other: SnapshotVersion): boolean {\n    return this.timestamp.isEqual(other.timestamp);\n  }\n\n  /** Returns a number representation of the version for use in spec tests. */\n  toMicroseconds(): number {\n    // Convert to microseconds.\n    return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n  }\n\n  toString(): string {\n    return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n  }\n\n  toTimestamp(): Timestamp {\n    return this.timestamp;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n *   http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n  key: K;\n  value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n  // visible for testing\n  root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n  constructor(\n    public comparator: Comparator<K>,\n    root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n  ) {\n    this.root = root ? root : LLRBNode.EMPTY;\n  }\n\n  // Returns a copy of the map, with the specified key/value added or replaced.\n  insert(key: K, value: V): SortedMap<K, V> {\n    return new SortedMap<K, V>(\n      this.comparator,\n      this.root\n        .insert(key, value, this.comparator)\n        .copy(null, null, LLRBNode.BLACK, null, null)\n    );\n  }\n\n  // Returns a copy of the map, with the specified key removed.\n  remove(key: K): SortedMap<K, V> {\n    return new SortedMap<K, V>(\n      this.comparator,\n      this.root\n        .remove(key, this.comparator)\n        .copy(null, null, LLRBNode.BLACK, null, null)\n    );\n  }\n\n  // Returns the value of the node with the given key, or null.\n  get(key: K): V | null {\n    let node = this.root;\n    while (!node.isEmpty()) {\n      const cmp = this.comparator(key, node.key);\n      if (cmp === 0) {\n        return node.value;\n      } else if (cmp < 0) {\n        node = node.left;\n      } else if (cmp > 0) {\n        node = node.right;\n      }\n    }\n    return null;\n  }\n\n  // Returns the index of the element in this sorted map, or -1 if it doesn't\n  // exist.\n  indexOf(key: K): number {\n    // Number of nodes that were pruned when descending right\n    let prunedNodes = 0;\n    let node = this.root;\n    while (!node.isEmpty()) {\n      const cmp = this.comparator(key, node.key);\n      if (cmp === 0) {\n        return prunedNodes + node.left.size;\n      } else if (cmp < 0) {\n        node = node.left;\n      } else {\n        // Count all nodes left of the node plus the node itself\n        prunedNodes += node.left.size + 1;\n        node = node.right;\n      }\n    }\n    // Node not found\n    return -1;\n  }\n\n  isEmpty(): boolean {\n    return this.root.isEmpty();\n  }\n\n  // Returns the total number of nodes in the map.\n  get size(): number {\n    return this.root.size;\n  }\n\n  // Returns the minimum key in the map.\n  minKey(): K | null {\n    return this.root.minKey();\n  }\n\n  // Returns the maximum key in the map.\n  maxKey(): K | null {\n    return this.root.maxKey();\n  }\n\n  // Traverses the map in key order and calls the specified action function\n  // for each key/value pair. If action returns true, traversal is aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  inorderTraversal<T>(action: (k: K, v: V) => T): T {\n    return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n  }\n\n  forEach(fn: (k: K, v: V) => void): void {\n    this.inorderTraversal((k, v) => {\n      fn(k, v);\n      return false;\n    });\n  }\n\n  toString(): string {\n    const descriptions: string[] = [];\n    this.inorderTraversal((k, v) => {\n      descriptions.push(`${k}:${v}`);\n      return false;\n    });\n    return `{${descriptions.join(', ')}}`;\n  }\n\n  // Traverses the map in reverse key order and calls the specified action\n  // function for each key/value pair. If action returns true, traversal is\n  // aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  reverseTraversal<T>(action: (k: K, v: V) => T): T {\n    return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n  }\n\n  // Returns an iterator over the SortedMap.\n  getIterator(): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n  }\n\n  getIteratorFrom(key: K): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n  }\n\n  getReverseIterator(): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n  }\n\n  getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n    return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n  }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n  private isReverse: boolean;\n  private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n  constructor(\n    node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n    startKey: K | null,\n    comparator: Comparator<K>,\n    isReverse: boolean\n  ) {\n    this.isReverse = isReverse;\n    this.nodeStack = [];\n\n    let cmp = 1;\n    while (!node.isEmpty()) {\n      cmp = startKey ? comparator(node.key, startKey) : 1;\n      // flip the comparison if we're going in reverse\n      if (startKey && isReverse) {\n        cmp *= -1;\n      }\n\n      if (cmp < 0) {\n        // This node is less than our start key. ignore it\n        if (this.isReverse) {\n          node = node.left;\n        } else {\n          node = node.right;\n        }\n      } else if (cmp === 0) {\n        // This node is exactly equal to our start key. Push it on the stack,\n        // but stop iterating;\n        this.nodeStack.push(node);\n        break;\n      } else {\n        // This node is greater than our start key, add it to the stack and move\n        // to the next one\n        this.nodeStack.push(node);\n        if (this.isReverse) {\n          node = node.right;\n        } else {\n          node = node.left;\n        }\n      }\n    }\n  }\n\n  getNext(): Entry<K, V> {\n    debugAssert(\n      this.nodeStack.length > 0,\n      'getNext() called on iterator when hasNext() is false.'\n    );\n\n    let node = this.nodeStack.pop()!;\n    const result = { key: node.key, value: node.value };\n\n    if (this.isReverse) {\n      node = node.left;\n      while (!node.isEmpty()) {\n        this.nodeStack.push(node);\n        node = node.right;\n      }\n    } else {\n      node = node.right;\n      while (!node.isEmpty()) {\n        this.nodeStack.push(node);\n        node = node.left;\n      }\n    }\n\n    return result;\n  }\n\n  hasNext(): boolean {\n    return this.nodeStack.length > 0;\n  }\n\n  peek(): Entry<K, V> | null {\n    if (this.nodeStack.length === 0) {\n      return null;\n    }\n\n    const node = this.nodeStack[this.nodeStack.length - 1];\n    return { key: node.key, value: node.value };\n  }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n  readonly color: boolean;\n  readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n  readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n  readonly size: number;\n\n  // Empty node is shared between all LLRB trees.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n  static RED = true;\n  static BLACK = false;\n\n  constructor(\n    public key: K,\n    public value: V,\n    color?: boolean,\n    left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n    right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n  ) {\n    this.color = color != null ? color : LLRBNode.RED;\n    this.left = left != null ? left : LLRBNode.EMPTY;\n    this.right = right != null ? right : LLRBNode.EMPTY;\n    this.size = this.left.size + 1 + this.right.size;\n  }\n\n  // Returns a copy of the current node, optionally replacing pieces of it.\n  copy(\n    key: K | null,\n    value: V | null,\n    color: boolean | null,\n    left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n    right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n  ): LLRBNode<K, V> {\n    return new LLRBNode<K, V>(\n      key != null ? key : this.key,\n      value != null ? value : this.value,\n      color != null ? color : this.color,\n      left != null ? left : this.left,\n      right != null ? right : this.right\n    );\n  }\n\n  isEmpty(): boolean {\n    return false;\n  }\n\n  // Traverses the tree in key order and calls the specified action function\n  // for each node. If action returns true, traversal is aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  inorderTraversal<T>(action: (k: K, v: V) => T): T {\n    return (\n      (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n      action(this.key, this.value) ||\n      (this.right as LLRBNode<K, V>).inorderTraversal(action)\n    );\n  }\n\n  // Traverses the tree in reverse key order and calls the specified action\n  // function for each node. If action returns true, traversal is aborted.\n  // Returns the first truthy value returned by action, or the last falsey\n  // value returned by action.\n  reverseTraversal<T>(action: (k: K, v: V) => T): T {\n    return (\n      (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n      action(this.key, this.value) ||\n      (this.left as LLRBNode<K, V>).reverseTraversal(action)\n    );\n  }\n\n  // Returns the minimum node in the tree.\n  private min(): LLRBNode<K, V> {\n    if (this.left.isEmpty()) {\n      return this;\n    } else {\n      return (this.left as LLRBNode<K, V>).min();\n    }\n  }\n\n  // Returns the maximum key in the tree.\n  minKey(): K | null {\n    return this.min().key;\n  }\n\n  // Returns the maximum key in the tree.\n  maxKey(): K | null {\n    if (this.right.isEmpty()) {\n      return this.key;\n    } else {\n      return this.right.maxKey();\n    }\n  }\n\n  // Returns new tree, with the key/value added.\n  insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n    let n: LLRBNode<K, V> = this;\n    const cmp = comparator(key, n.key);\n    if (cmp < 0) {\n      n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n    } else if (cmp === 0) {\n      n = n.copy(null, value, null, null, null);\n    } else {\n      n = n.copy(\n        null,\n        null,\n        null,\n        null,\n        n.right.insert(key, value, comparator)\n      );\n    }\n    return n.fixUp();\n  }\n\n  private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n    if (this.left.isEmpty()) {\n      return LLRBNode.EMPTY;\n    }\n    let n: LLRBNode<K, V> = this;\n    if (!n.left.isRed() && !n.left.left.isRed()) {\n      n = n.moveRedLeft();\n    }\n    n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n    return n.fixUp();\n  }\n\n  // Returns new tree, with the specified item removed.\n  remove(\n    key: K,\n    comparator: Comparator<K>\n  ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n    let smallest: LLRBNode<K, V>;\n    let n: LLRBNode<K, V> = this;\n    if (comparator(key, n.key) < 0) {\n      if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n        n = n.moveRedLeft();\n      }\n      n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n    } else {\n      if (n.left.isRed()) {\n        n = n.rotateRight();\n      }\n      if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n        n = n.moveRedRight();\n      }\n      if (comparator(key, n.key) === 0) {\n        if (n.right.isEmpty()) {\n          return LLRBNode.EMPTY;\n        } else {\n          smallest = (n.right as LLRBNode<K, V>).min();\n          n = n.copy(\n            smallest.key,\n            smallest.value,\n            null,\n            null,\n            (n.right as LLRBNode<K, V>).removeMin()\n          );\n        }\n      }\n      n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n    }\n    return n.fixUp();\n  }\n\n  isRed(): boolean {\n    return this.color;\n  }\n\n  // Returns new tree after performing any needed rotations.\n  private fixUp(): LLRBNode<K, V> {\n    let n: LLRBNode<K, V> = this;\n    if (n.right.isRed() && !n.left.isRed()) {\n      n = n.rotateLeft();\n    }\n    if (n.left.isRed() && n.left.left.isRed()) {\n      n = n.rotateRight();\n    }\n    if (n.left.isRed() && n.right.isRed()) {\n      n = n.colorFlip();\n    }\n    return n;\n  }\n\n  private moveRedLeft(): LLRBNode<K, V> {\n    let n = this.colorFlip();\n    if (n.right.left.isRed()) {\n      n = n.copy(\n        null,\n        null,\n        null,\n        null,\n        (n.right as LLRBNode<K, V>).rotateRight()\n      );\n      n = n.rotateLeft();\n      n = n.colorFlip();\n    }\n    return n;\n  }\n\n  private moveRedRight(): LLRBNode<K, V> {\n    let n = this.colorFlip();\n    if (n.left.left.isRed()) {\n      n = n.rotateRight();\n      n = n.colorFlip();\n    }\n    return n;\n  }\n\n  private rotateLeft(): LLRBNode<K, V> {\n    const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n    return (this.right as LLRBNode<K, V>).copy(\n      null,\n      null,\n      this.color,\n      nl,\n      null\n    );\n  }\n\n  private rotateRight(): LLRBNode<K, V> {\n    const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n    return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n  }\n\n  private colorFlip(): LLRBNode<K, V> {\n    const left = this.left.copy(null, null, !this.left.color, null, null);\n    const right = this.right.copy(null, null, !this.right.color, null, null);\n    return this.copy(null, null, !this.color, left, right);\n  }\n\n  // For testing.\n  checkMaxDepth(): boolean {\n    const blackDepth = this.check();\n    if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  // In a balanced RB tree, the black-depth (number of black nodes) from root to\n  // leaves is equal on both sides.  This function verifies that or asserts.\n  protected check(): number {\n    if (this.isRed() && this.left.isRed()) {\n      throw fail(0xaad2, 'Red node has red child', {\n        key: this.key,\n        value: this.value\n      });\n    }\n    if (this.right.isRed()) {\n      throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n        key: this.key,\n        value: this.value\n      });\n    }\n    const blackDepth = (this.left as LLRBNode<K, V>).check();\n    if (blackDepth !== (this.right as LLRBNode<K, V>).check()) {\n      throw fail(0x6d2d, 'Black depths differ');\n    } else {\n      return blackDepth + (this.isRed() ? 0 : 1);\n    }\n  }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode<K, V> {\n  get key(): never {\n    throw fail(0xe1a6, 'LLRBEmptyNode has no key.');\n  }\n  get value(): never {\n    throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n  }\n  get color(): never {\n    throw fail(0x4157, 'LLRBEmptyNode has no color.');\n  }\n  get left(): never {\n    throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n  }\n  get right(): never {\n    throw fail(0x901e, 'LLRBEmptyNode has no right child.');\n  }\n  size = 0;\n\n  // Returns a copy of the current node.\n  copy(\n    key: K | null,\n    value: V | null,\n    color: boolean | null,\n    left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n    right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n  ): LLRBEmptyNode<K, V> {\n    return this;\n  }\n\n  // Returns a copy of the tree, with the specified key/value added.\n  insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n    return new LLRBNode<K, V>(key, value);\n  }\n\n  // Returns a copy of the tree, with the specified key removed.\n  remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n    return this;\n  }\n\n  isEmpty(): boolean {\n    return true;\n  }\n\n  inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n    return false;\n  }\n\n  reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n    return false;\n  }\n\n  minKey(): K | null {\n    return null;\n  }\n\n  maxKey(): K | null {\n    return null;\n  }\n\n  isRed(): boolean {\n    return false;\n  }\n\n  // For testing.\n  checkMaxDepth(): boolean {\n    return true;\n  }\n\n  protected check(): 0 {\n    return 0;\n  }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet<T> {\n  private data: SortedMap<T, boolean>;\n\n  constructor(private comparator: (left: T, right: T) => number) {\n    this.data = new SortedMap<T, boolean>(this.comparator);\n  }\n\n  has(elem: T): boolean {\n    return this.data.get(elem) !== null;\n  }\n\n  first(): T | null {\n    return this.data.minKey();\n  }\n\n  last(): T | null {\n    return this.data.maxKey();\n  }\n\n  get size(): number {\n    return this.data.size;\n  }\n\n  indexOf(elem: T): number {\n    return this.data.indexOf(elem);\n  }\n\n  /** Iterates elements in order defined by \"comparator\" */\n  forEach(cb: (elem: T) => void): void {\n    this.data.inorderTraversal((k: T, v: boolean) => {\n      cb(k);\n      return false;\n    });\n  }\n\n  /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */\n  forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n    const iter = this.data.getIteratorFrom(range[0]);\n    while (iter.hasNext()) {\n      const elem = iter.getNext();\n      if (this.comparator(elem.key, range[1]) >= 0) {\n        return;\n      }\n      cb(elem.key);\n    }\n  }\n\n  /**\n   * Iterates over `elem`s such that: start &lt;= elem until false is returned.\n   */\n  forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n    let iter: SortedMapIterator<T, boolean>;\n    if (start !== undefined) {\n      iter = this.data.getIteratorFrom(start);\n    } else {\n      iter = this.data.getIterator();\n    }\n    while (iter.hasNext()) {\n      const elem = iter.getNext();\n      const result = cb(elem.key);\n      if (!result) {\n        return;\n      }\n    }\n  }\n\n  /** Finds the least element greater than or equal to `elem`. */\n  firstAfterOrEqual(elem: T): T | null {\n    const iter = this.data.getIteratorFrom(elem);\n    return iter.hasNext() ? iter.getNext().key : null;\n  }\n\n  getIterator(): SortedSetIterator<T> {\n    return new SortedSetIterator<T>(this.data.getIterator());\n  }\n\n  getIteratorFrom(key: T): SortedSetIterator<T> {\n    return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n  }\n\n  /** Inserts or updates an element */\n  add(elem: T): SortedSet<T> {\n    return this.copy(this.data.remove(elem).insert(elem, true));\n  }\n\n  /** Deletes an element */\n  delete(elem: T): SortedSet<T> {\n    if (!this.has(elem)) {\n      return this;\n    }\n    return this.copy(this.data.remove(elem));\n  }\n\n  isEmpty(): boolean {\n    return this.data.isEmpty();\n  }\n\n  unionWith(other: SortedSet<T>): SortedSet<T> {\n    let result: SortedSet<T> = this;\n\n    // Make sure `result` always refers to the larger one of the two sets.\n    if (result.size < other.size) {\n      result = other;\n      other = this;\n    }\n\n    other.forEach(elem => {\n      result = result.add(elem);\n    });\n    return result;\n  }\n\n  isEqual(other: SortedSet<T>): boolean {\n    if (!(other instanceof SortedSet)) {\n      return false;\n    }\n    if (this.size !== other.size) {\n      return false;\n    }\n\n    const thisIt = this.data.getIterator();\n    const otherIt = other.data.getIterator();\n    while (thisIt.hasNext()) {\n      const thisElem = thisIt.getNext().key;\n      const otherElem = otherIt.getNext().key;\n      if (this.comparator(thisElem, otherElem) !== 0) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  toArray(): T[] {\n    const res: T[] = [];\n    this.forEach(targetId => {\n      res.push(targetId);\n    });\n    return res;\n  }\n\n  toString(): string {\n    const result: T[] = [];\n    this.forEach(elem => result.push(elem));\n    return 'SortedSet(' + result.toString() + ')';\n  }\n\n  private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n    const result = new SortedSet(this.comparator);\n    result.data = data;\n    return result;\n  }\n}\n\nexport class SortedSetIterator<T> {\n  constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n  getNext(): T {\n    return this.iter.getNext().key;\n  }\n\n  hasNext(): boolean {\n    return this.iter.hasNext();\n  }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets<T>(\n  before: SortedSet<T>,\n  after: SortedSet<T>,\n  comparator: (l: T, r: T) => number,\n  onAdd: (entry: T) => void,\n  onRemove: (entry: T) => void\n): void {\n  const beforeIt = before.getIterator();\n  const afterIt = after.getIterator();\n\n  let beforeValue = advanceIterator(beforeIt);\n  let afterValue = advanceIterator(afterIt);\n\n  // Walk through the two sets at the same time, using the ordering defined by\n  // `comparator`.\n  while (beforeValue || afterValue) {\n    let added = false;\n    let removed = false;\n\n    if (beforeValue && afterValue) {\n      const cmp = comparator(beforeValue, afterValue);\n      if (cmp < 0) {\n        // The element was removed if the next element in our ordered\n        // walkthrough is only in `before`.\n        removed = true;\n      } else if (cmp > 0) {\n        // The element was added if the next element in our ordered walkthrough\n        // is only in `after`.\n        added = true;\n      }\n    } else if (beforeValue != null) {\n      removed = true;\n    } else {\n      added = true;\n    }\n\n    if (added) {\n      onAdd(afterValue!);\n      afterValue = advanceIterator(afterIt);\n    } else if (removed) {\n      onRemove(beforeValue!);\n      beforeValue = advanceIterator(beforeIt);\n    } else {\n      beforeValue = advanceIterator(beforeIt);\n      afterValue = advanceIterator(afterIt);\n    }\n  }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator<T>(it: SortedSetIterator<T>): T | undefined {\n  return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  MapValue as ProtoMapValue,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject<T> {\n  [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n  constructor(readonly value: { mapValue: ProtoMapValue }) {\n    debugAssert(\n      !isServerTimestamp(value),\n      'ServerTimestamps should be converted to ServerTimestampValue'\n    );\n  }\n\n  static empty(): ObjectValue {\n    return new ObjectValue({ mapValue: {} });\n  }\n\n  /**\n   * Returns the value at the given path or null.\n   *\n   * @param path - the path to search\n   * @returns The value at the path or null if the path is not set.\n   */\n  field(path: FieldPath): ProtoValue | null {\n    if (path.isEmpty()) {\n      return this.value;\n    } else {\n      let currentLevel: ProtoValue = this.value;\n      for (let i = 0; i < path.length - 1; ++i) {\n        currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n        if (!isMapValue(currentLevel)) {\n          return null;\n        }\n      }\n      currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n      return currentLevel || null;\n    }\n  }\n\n  /**\n   * Sets the field to the provided value.\n   *\n   * @param path - The field path to set.\n   * @param value - The value to set.\n   */\n  set(path: FieldPath, value: ProtoValue): void {\n    debugAssert(\n      !path.isEmpty(),\n      'Cannot set field for empty path on ObjectValue'\n    );\n    const fieldsMap = this.getFieldsMap(path.popLast());\n    fieldsMap[path.lastSegment()] = deepClone(value);\n  }\n\n  /**\n   * Sets the provided fields to the provided values.\n   *\n   * @param data - A map of fields to values (or null for deletes).\n   */\n  setAll(data: Map<FieldPath, ProtoValue | null>): void {\n    let parent = FieldPath.emptyPath();\n\n    let upserts: { [key: string]: ProtoValue } = {};\n    let deletes: string[] = [];\n\n    data.forEach((value, path) => {\n      if (!parent.isImmediateParentOf(path)) {\n        // Insert the accumulated changes at this parent location\n        const fieldsMap = this.getFieldsMap(parent);\n        this.applyChanges(fieldsMap, upserts, deletes);\n        upserts = {};\n        deletes = [];\n        parent = path.popLast();\n      }\n\n      if (value) {\n        upserts[path.lastSegment()] = deepClone(value);\n      } else {\n        deletes.push(path.lastSegment());\n      }\n    });\n\n    const fieldsMap = this.getFieldsMap(parent);\n    this.applyChanges(fieldsMap, upserts, deletes);\n  }\n\n  /**\n   * Removes the field at the specified path. If there is no field at the\n   * specified path, nothing is changed.\n   *\n   * @param path - The field path to remove.\n   */\n  delete(path: FieldPath): void {\n    debugAssert(\n      !path.isEmpty(),\n      'Cannot delete field for empty path on ObjectValue'\n    );\n    const nestedValue = this.field(path.popLast());\n    if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n      delete nestedValue.mapValue.fields[path.lastSegment()];\n    }\n  }\n\n  isEqual(other: ObjectValue): boolean {\n    return valueEquals(this.value, other.value);\n  }\n\n  /**\n   * Returns the map that contains the leaf element of `path`. If the parent\n   * entry does not yet exist, or if it is not a map, a new map will be created.\n   */\n  private getFieldsMap(path: FieldPath): Record<string, ProtoValue> {\n    let current = this.value;\n\n    if (!current.mapValue!.fields) {\n      current.mapValue = { fields: {} };\n    }\n\n    for (let i = 0; i < path.length; ++i) {\n      let next = current.mapValue!.fields![path.get(i)];\n      if (!isMapValue(next) || !next.mapValue.fields) {\n        next = { mapValue: { fields: {} } };\n        current.mapValue!.fields![path.get(i)] = next;\n      }\n      current = next as { mapValue: ProtoMapValue };\n    }\n\n    return current.mapValue!.fields!;\n  }\n\n  /**\n   * Modifies `fieldsMap` by adding, replacing or deleting the specified\n   * entries.\n   */\n  private applyChanges(\n    fieldsMap: Record<string, ProtoValue>,\n    inserts: { [key: string]: ProtoValue },\n    deletes: string[]\n  ): void {\n    forEach(inserts, (key, val) => (fieldsMap[key] = val));\n    for (const field of deletes) {\n      delete fieldsMap[field];\n    }\n  }\n\n  clone(): ObjectValue {\n    return new ObjectValue(\n      deepClone(this.value) as { mapValue: ProtoMapValue }\n    );\n  }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n  const fields: FieldPath[] = [];\n  forEach(value!.fields, (key, value) => {\n    const currentPath = new FieldPath([key]);\n    if (isMapValue(value)) {\n      const nestedMask = extractFieldMask(value.mapValue!);\n      const nestedFields = nestedMask.fields;\n      if (nestedFields.length === 0) {\n        // Preserve the empty map by adding it to the FieldMask.\n        fields.push(currentPath);\n      } else {\n        // For nested and non-empty ObjectValues, add the FieldPath of the\n        // leaf nodes.\n        for (const nestedPath of nestedFields) {\n          fields.push(currentPath.child(nestedPath));\n        }\n      }\n    } else {\n      // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n      // nodes.\n      fields.push(currentPath);\n    }\n  });\n  return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n  Bound,\n  boundSortsAfterDocument,\n  boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n  canonifyTarget,\n  newTarget,\n  stringifyTarget,\n  Target,\n  targetEquals\n} from './target';\n\nexport const enum LimitType {\n  First = 'F',\n  Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n  readonly path: ResourcePath;\n  readonly collectionGroup: string | null;\n  readonly explicitOrderBy: OrderBy[];\n  readonly filters: Filter[];\n  readonly limit: number | null;\n  readonly limitType: LimitType;\n  readonly startAt: Bound | null;\n  readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n  memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n  // The corresponding `Target` of this `Query` instance, for use with\n  // non-aggregate queries.\n  memoizedTarget: Target | null = null;\n\n  // The corresponding `Target` of this `Query` instance, for use with\n  // aggregate queries. Unlike targets for non-aggregate queries,\n  // aggregate query targets do not contain normalized order-bys, they only\n  // contain explicit order-bys.\n  memoizedAggregateTarget: Target | null = null;\n\n  /**\n   * Initializes a Query with a path and optional additional query constraints.\n   * Path must currently be empty if this is a collection group query.\n   */\n  constructor(\n    readonly path: ResourcePath,\n    readonly collectionGroup: string | null = null,\n    readonly explicitOrderBy: OrderBy[] = [],\n    readonly filters: Filter[] = [],\n    readonly limit: number | null = null,\n    readonly limitType: LimitType = LimitType.First,\n    readonly startAt: Bound | null = null,\n    readonly endAt: Bound | null = null\n  ) {\n    if (this.startAt) {\n      debugAssert(\n        this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n        'Bound is longer than orderBy'\n      );\n    }\n    if (this.endAt) {\n      debugAssert(\n        this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n        'Bound is longer than orderBy'\n      );\n    }\n  }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n  path: ResourcePath,\n  collectionGroup: string | null,\n  explicitOrderBy: OrderBy[],\n  filters: Filter[],\n  limit: number | null,\n  limitType: LimitType,\n  startAt: Bound | null,\n  endAt: Bound | null\n): Query {\n  return new QueryImpl(\n    path,\n    collectionGroup,\n    explicitOrderBy,\n    filters,\n    limit,\n    limitType,\n    startAt,\n    endAt\n  );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n  return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n  query: Query,\n  path: ResourcePath\n): Query {\n  return new QueryImpl(\n    path,\n    /*collectionGroup=*/ null,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n  return (\n    query.filters.length === 0 &&\n    query.limit === null &&\n    query.startAt == null &&\n    query.endAt == null &&\n    (query.explicitOrderBy.length === 0 ||\n      (query.explicitOrderBy.length === 1 &&\n        query.explicitOrderBy[0].field.isKeyField()))\n  );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet<FieldPath> {\n  let result = new SortedSet<FieldPath>(FieldPath.comparator);\n  query.filters.forEach((filter: Filter) => {\n    const subFilters = filter.getFlattenedFilters();\n    subFilters.forEach((filter: FieldFilter) => {\n      if (filter.isInequality()) {\n        result = result.add(filter.field);\n      }\n    });\n  });\n  return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n  return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n  return (\n    DocumentKey.isDocumentKey(query.path) &&\n    query.collectionGroup === null &&\n    query.filters.length === 0\n  );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n  return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n  const queryImpl = debugCast(query, QueryImpl);\n  if (queryImpl.memoizedNormalizedOrderBy === null) {\n    queryImpl.memoizedNormalizedOrderBy = [];\n    const fieldsNormalized = new Set<string>();\n\n    // Any explicit order by fields should be added as is.\n    for (const orderBy of queryImpl.explicitOrderBy) {\n      queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n      fieldsNormalized.add(orderBy.field.canonicalString());\n    }\n\n    // The order of the implicit ordering always matches the last explicit order by.\n    const lastDirection =\n      queryImpl.explicitOrderBy.length > 0\n        ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n        : Direction.ASCENDING;\n\n    // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n    // order. When there are multiple inequality filters on the same field, the field should be added\n    // only once.\n    // Note: `SortedSet<FieldPath>` sorts the key field before other fields. However, we want the key\n    // field to be sorted last.\n    const inequalityFields: SortedSet<FieldPath> =\n      getInequalityFilterFields(queryImpl);\n    inequalityFields.forEach(field => {\n      if (\n        !fieldsNormalized.has(field.canonicalString()) &&\n        !field.isKeyField()\n      ) {\n        queryImpl.memoizedNormalizedOrderBy!.push(\n          new OrderBy(field, lastDirection)\n        );\n      }\n    });\n\n    // Add the document key field to the last if it is not explicitly ordered.\n    if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n      queryImpl.memoizedNormalizedOrderBy.push(\n        new OrderBy(FieldPath.keyField(), lastDirection)\n      );\n    }\n  }\n  return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n  const queryImpl = debugCast(query, QueryImpl);\n  if (!queryImpl.memoizedTarget) {\n    queryImpl.memoizedTarget = _queryToTarget(\n      queryImpl,\n      queryNormalizedOrderBy(query)\n    );\n  }\n\n  return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n  const queryImpl = debugCast(query, QueryImpl);\n\n  if (!queryImpl.memoizedAggregateTarget) {\n    // Do not include implicit order-bys for aggregate queries.\n    queryImpl.memoizedAggregateTarget = _queryToTarget(\n      queryImpl,\n      query.explicitOrderBy\n    );\n  }\n\n  return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n  if (queryImpl.limitType === LimitType.First) {\n    return newTarget(\n      queryImpl.path,\n      queryImpl.collectionGroup,\n      orderBys,\n      queryImpl.filters,\n      queryImpl.limit,\n      queryImpl.startAt,\n      queryImpl.endAt\n    );\n  } else {\n    // Flip the orderBy directions since we want the last results\n    orderBys = orderBys.map(orderBy => {\n      const dir =\n        orderBy.dir === Direction.DESCENDING\n          ? Direction.ASCENDING\n          : Direction.DESCENDING;\n      return new OrderBy(orderBy.field, dir);\n    });\n\n    // We need to swap the cursors to match the now-flipped query ordering.\n    const startAt = queryImpl.endAt\n      ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n      : null;\n    const endAt = queryImpl.startAt\n      ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n      : null;\n\n    // Now return as a LimitType.First query.\n    return newTarget(\n      queryImpl.path,\n      queryImpl.collectionGroup,\n      orderBys,\n      queryImpl.filters,\n      queryImpl.limit,\n      startAt,\n      endAt\n    );\n  }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n  debugAssert(\n    !isDocumentQuery(query),\n    'No filtering allowed for document query'\n  );\n\n  const newFilters = query.filters.concat([filter]);\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    newFilters,\n    query.limit,\n    query.limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n  debugAssert(\n    !query.startAt && !query.endAt,\n    'Bounds must be set after orderBy'\n  );\n  // TODO(dimond): validate that orderBy does not list the same key twice.\n  const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    newOrderBy,\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\nexport function queryWithLimit(\n  query: Query,\n  limit: number | null,\n  limitType: LimitType\n): Query {\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    limit,\n    limitType,\n    query.startAt,\n    query.endAt\n  );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    bound,\n    query.endAt\n  );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n  return new QueryImpl(\n    query.path,\n    query.collectionGroup,\n    query.explicitOrderBy.slice(),\n    query.filters.slice(),\n    query.limit,\n    query.limitType,\n    query.startAt,\n    bound\n  );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n  return (\n    targetEquals(queryToTarget(left), queryToTarget(right)) &&\n    left.limitType === right.limitType\n  );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n  return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n  return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n    query.limitType\n  })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n  return (\n    doc.isFoundDocument() &&\n    queryMatchesPathAndCollectionGroup(query, doc) &&\n    queryMatchesOrderBy(query, doc) &&\n    queryMatchesFilters(query, doc) &&\n    queryMatchesBounds(query, doc)\n  );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n  query: Query,\n  doc: Document\n): boolean {\n  const docPath = doc.key.path;\n  if (query.collectionGroup !== null) {\n    // NOTE: this.path is currently always empty since we don't expose Collection\n    // Group queries rooted at a document path yet.\n    return (\n      doc.key.hasCollectionId(query.collectionGroup) &&\n      query.path.isPrefixOf(docPath)\n    );\n  } else if (DocumentKey.isDocumentKey(query.path)) {\n    // exact match for document queries\n    return query.path.isEqual(docPath);\n  } else {\n    // shallow ancestor queries by default\n    return query.path.isImmediateParentOf(docPath);\n  }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n  // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n  // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n  // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n  // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n  // A document with content of {b:1} matches the filters, but does not match the orderBy because\n  // it's missing the field 'a'.\n  for (const orderBy of queryNormalizedOrderBy(query)) {\n    // order-by key always matches\n    if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n  for (const filter of query.filters) {\n    if (!filter.matches(doc)) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n  if (\n    query.startAt &&\n    !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n  ) {\n    return false;\n  }\n  if (\n    query.endAt &&\n    !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n  ) {\n    return false;\n  }\n  return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n  return (\n    query.collectionGroup ||\n    (query.path.length % 2 === 1\n      ? query.path.lastSegment()\n      : query.path.get(query.path.length - 2))\n  );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n  query: Query\n): (d1: Document, d2: Document) => number {\n  return (d1: Document, d2: Document): number => {\n    let comparedOnKeyField = false;\n    for (const orderBy of queryNormalizedOrderBy(query)) {\n      const comp = compareDocs(orderBy, d1, d2);\n      if (comp !== 0) {\n        return comp;\n      }\n      comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n    }\n    // Assert that we actually compared by key\n    debugAssert(\n      comparedOnKeyField,\n      \"orderBy used that doesn't compare on key field\"\n    );\n    return 0;\n  };\n}\n\nexport function compareDocs(\n  orderBy: OrderBy,\n  d1: Document,\n  d2: Document\n): number {\n  const comparison = orderBy.field.isKeyField()\n    ? DocumentKey.comparator(d1.key, d2.key)\n    : compareDocumentsByField(orderBy.field, d1, d2);\n  switch (orderBy.dir) {\n    case Direction.ASCENDING:\n      return comparison;\n    case Direction.DESCENDING:\n      return -1 * comparison;\n    default:\n      return fail(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n  readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n  if (serializer.useProto3Json) {\n    if (isNaN(value)) {\n      return { doubleValue: 'NaN' };\n    } else if (value === Infinity) {\n      return { doubleValue: 'Infinity' };\n    } else if (value === -Infinity) {\n      return { doubleValue: '-Infinity' };\n    }\n  }\n  return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n  return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n  return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n  CompositeFilter,\n  compositeFilterIsFlatConjunction,\n  CompositeOperator,\n  FieldFilter,\n  Filter,\n  Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n  LimitType,\n  newQuery,\n  newQueryForPath,\n  Query,\n  queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { RemoteTargetId } from '../core/types';\nimport { Bytes } from '../lite-api/bytes';\nimport { GeoPoint } from '../lite-api/geo_point';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n  DeleteMutation,\n  FieldTransform,\n  Mutation,\n  MutationResult,\n  PatchMutation,\n  Precondition,\n  SetMutation,\n  VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { PipelineStreamElement } from '../model/pipeline_stream_element';\nimport {\n  ArrayRemoveTransformOperation,\n  ArrayUnionTransformOperation,\n  NumericIncrementTransformOperation,\n  ServerTimestampTransform,\n  TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n  ApiClientObjectMap as ProtoApiClientObjectMap,\n  BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n  CompositeFilterOp as ProtoCompositeFilterOp,\n  Cursor as ProtoCursor,\n  Document as ProtoDocument,\n  DocumentMask as ProtoDocumentMask,\n  DocumentsTarget as ProtoDocumentsTarget,\n  FieldFilterOp as ProtoFieldFilterOp,\n  FieldReference as ProtoFieldReference,\n  FieldTransform as ProtoFieldTransform,\n  Filter as ProtoFilter,\n  ListenResponse as ProtoListenResponse,\n  Order as ProtoOrder,\n  OrderDirection as ProtoOrderDirection,\n  Precondition as ProtoPrecondition,\n  QueryTarget as ProtoQueryTarget,\n  RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n  Aggregation as ProtoAggregation,\n  Status as ProtoStatus,\n  Target as ProtoTarget,\n  TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n  Timestamp as ProtoTimestamp,\n  Write as ProtoWrite,\n  WriteResult as ProtoWriteResult,\n  Value as ProtoValue,\n  MapValue as ProtoMapValue,\n  ExecutePipelineResponse as ProtoExecutePipelineResponse,\n  Pipeline as ProtoPipeline\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n  DocumentWatchChange,\n  ExistenceFilterChange,\n  WatchChange,\n  WatchTargetChange,\n  WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n  const dirs: { [dir: string]: ProtoOrderDirection } = {};\n  dirs[Direction.ASCENDING] = 'ASCENDING';\n  dirs[Direction.DESCENDING] = 'DESCENDING';\n  return dirs;\n})();\n\nconst OPERATORS = (() => {\n  const ops: { [op: string]: ProtoFieldFilterOp } = {};\n  ops[Operator.LESS_THAN] = 'LESS_THAN';\n  ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n  ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n  ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n  ops[Operator.EQUAL] = 'EQUAL';\n  ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n  ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n  ops[Operator.IN] = 'IN';\n  ops[Operator.NOT_IN] = 'NOT_IN';\n  ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n  return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n  const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n  ops[CompositeOperator.AND] = 'AND';\n  ops[CompositeOperator.OR] = 'OR';\n  return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n  debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n  constructor(\n    readonly databaseId: DatabaseId,\n    readonly useProto3Json: boolean\n  ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n  const code =\n    status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n  return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */\nexport function toInt32Proto(\n  serializer: JsonProtoSerializer,\n  val: number | null\n): number | { value: number } | null {\n  if (serializer.useProto3Json || isNullOrUndefined(val)) {\n    return val;\n  } else {\n    return { value: val };\n  }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n  val: number | { value: number } | undefined\n): number | null {\n  let result;\n  if (typeof val === 'object') {\n    result = val.value;\n  } else {\n    result = val;\n  }\n  return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n  serializer: JsonProtoSerializer,\n  timestamp: Timestamp\n): ProtoTimestamp {\n  if (serializer.useProto3Json) {\n    // Serialize to ISO-8601 date format, but with full nano resolution.\n    // Since JS Date has only millis, let's only use it for the seconds and\n    // then manually add the fractions to the end.\n    const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n    // Remove .xxx frac part and Z in the end.\n    const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n    // Pad the fraction out to 9 digits (nanos).\n    const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n    return `${strUntilSeconds}.${nanoStr}Z`;\n  } else {\n    return {\n      seconds: '' + timestamp.seconds,\n      nanos: timestamp.nanoseconds\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    } as any;\n  }\n}\n\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function fromTimestamp(date: ProtoTimestamp): Timestamp {\n  const timestamp = normalizeTimestamp(date);\n  return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n  serializer: JsonProtoSerializer,\n  bytes: ByteString\n): string | Uint8Array {\n  if (serializer.useProto3Json) {\n    return bytes.toBase64();\n  } else {\n    return bytes.toUint8Array();\n  }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n  serializer: JsonProtoSerializer,\n  value: string | Uint8Array | undefined\n): ByteString {\n  if (serializer.useProto3Json) {\n    hardAssert(\n      value === undefined || typeof value === 'string',\n      0xe30b,\n      'value must be undefined or a string when using proto3 Json'\n    );\n    return ByteString.fromBase64String(value ? value : '');\n  } else {\n    hardAssert(\n      value === undefined ||\n        // Check if the value is an instance of both Buffer and Uint8Array,\n        // despite the fact that Buffer extends Uint8Array. In some\n        // environments, such as jsdom, the prototype chain of Buffer\n        // does not indicate that it extends Uint8Array.\n        value instanceof Buffer ||\n        value instanceof Uint8Array,\n      0x3f41,\n      'value must be undefined, Buffer, or Uint8Array'\n    );\n    return ByteString.fromUint8Array(value ? value : new Uint8Array());\n  }\n}\n\nexport function toVersion(\n  serializer: JsonProtoSerializer,\n  version: SnapshotVersion\n): ProtoTimestamp {\n  return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n  hardAssert(!!version, 0xc050, \"Trying to deserialize version that isn't set\");\n  return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n  databaseId: DatabaseId,\n  path: ResourcePath\n): string {\n  return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n  databaseId: DatabaseId,\n  path?: ResourcePath\n): ResourcePath {\n  const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n  return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n  const resource = ResourcePath.fromString(name);\n  hardAssert(\n    isValidResourceName(resource),\n    0x27ce,\n    'Tried to deserialize invalid key',\n    { key: resource.toString() }\n  );\n  return resource;\n}\n\nexport function toName(\n  serializer: JsonProtoSerializer,\n  key: DocumentKey\n): string {\n  return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n  serializer: JsonProtoSerializer,\n  name: string\n): DocumentKey {\n  const resource = fromResourceName(name);\n\n  if (resource.get(1) !== serializer.databaseId.projectId) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Tried to deserialize key from different project: ' +\n        resource.get(1) +\n        ' vs ' +\n        serializer.databaseId.projectId\n    );\n  }\n\n  if (resource.get(3) !== serializer.databaseId.database) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Tried to deserialize key from different database: ' +\n        resource.get(3) +\n        ' vs ' +\n        serializer.databaseId.database\n    );\n  }\n  return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n  serializer: JsonProtoSerializer,\n  path: ResourcePath\n): string {\n  return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n  const resourceName = fromResourceName(name);\n  // In v1beta1 queries for collections at the root did not have a trailing\n  // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n  // ability to read the v1beta1 form for compatibility with queries persisted\n  // in the local target cache.\n  if (resourceName.length === 4) {\n    return ResourcePath.emptyPath();\n  }\n  return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n  const path = new ResourcePath([\n    'projects',\n    serializer.databaseId.projectId,\n    'databases',\n    serializer.databaseId.database\n  ]);\n  return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n  return new ResourcePath([\n    'projects',\n    databaseId.projectId,\n    'databases',\n    databaseId.database\n  ]);\n}\n\nfunction extractLocalPathFromResourceName(\n  resourceName: ResourcePath\n): ResourcePath {\n  hardAssert(\n    resourceName.length > 4 && resourceName.get(4) === 'documents',\n    0x71a3,\n    'tried to deserialize invalid key',\n    { key: resourceName.toString() }\n  );\n  return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n  serializer: JsonProtoSerializer,\n  key: DocumentKey,\n  fields: ObjectValue\n): ProtoDocument {\n  return {\n    name: toName(serializer, key),\n    fields: fields.value.mapValue.fields\n  };\n}\n\nexport function toDocument(\n  serializer: JsonProtoSerializer,\n  document: MutableDocument\n): ProtoDocument {\n  debugAssert(\n    !document.hasLocalMutations,\n    \"Can't serialize documents with mutations.\"\n  );\n  return {\n    name: toName(serializer, document.key),\n    fields: document.data.value.mapValue.fields,\n    updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n    createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n  };\n}\n\nexport function fromPipelineResponse(\n  serializer: JsonProtoSerializer,\n  proto: ProtoExecutePipelineResponse,\n  document?: ProtoDocument\n): PipelineStreamElement {\n  const output: PipelineStreamElement = {};\n  if (proto.transaction?.length) {\n    output.transaction = proto.transaction;\n  }\n  const executionTime = proto.executionTime\n    ? fromVersion(proto.executionTime)\n    : undefined;\n  output.executionTime = executionTime;\n\n  if (!!document) {\n    output.key = document.name\n      ? fromName(serializer, document.name)\n      : undefined;\n\n    output.fields = new ObjectValue({ mapValue: { fields: document.fields } });\n\n    output.createTime = document.createTime\n      ? fromVersion(document.createTime!)\n      : undefined;\n    output.updateTime = document.updateTime\n      ? fromVersion(document.updateTime!)\n      : undefined;\n  }\n  return output;\n}\n\nexport function fromDocument(\n  serializer: JsonProtoSerializer,\n  document: ProtoDocument,\n  hasCommittedMutations?: boolean\n): MutableDocument {\n  const key = fromName(serializer, document.name!);\n  const version = fromVersion(document.updateTime!);\n  // If we read a document from persistence that is missing createTime, it's due\n  // to older SDK versions not storing this information. In such cases, we'll\n  // set the createTime to zero. This can be removed in the long term.\n  const createTime = document.createTime\n    ? fromVersion(document.createTime)\n    : SnapshotVersion.min();\n  const data = new ObjectValue({ mapValue: { fields: document.fields } });\n  const result = MutableDocument.newFoundDocument(\n    key,\n    version,\n    createTime,\n    data\n  );\n  if (hasCommittedMutations) {\n    result.setHasCommittedMutations();\n  }\n  return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n  serializer: JsonProtoSerializer,\n  doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n  hardAssert(\n    !!doc.found,\n    0xaa33,\n    'Tried to deserialize a found document from a missing document.'\n  );\n  assertPresent(doc.found.name, 'doc.found.name');\n  assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n  const key = fromName(serializer, doc.found.name);\n  const version = fromVersion(doc.found.updateTime);\n  const createTime = doc.found.createTime\n    ? fromVersion(doc.found.createTime)\n    : SnapshotVersion.min();\n  const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n  return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n  serializer: JsonProtoSerializer,\n  result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n  hardAssert(\n    !!result.missing,\n    0x0f36,\n    'Tried to deserialize a missing document from a found document.'\n  );\n  hardAssert(\n    !!result.readTime,\n    0x5995,\n    'Tried to deserialize a missing document without a read time.'\n  );\n  const key = fromName(serializer, result.missing);\n  const version = fromVersion(result.readTime);\n  return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n  serializer: JsonProtoSerializer,\n  result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n  if ('found' in result) {\n    return fromFound(serializer, result);\n  } else if ('missing' in result) {\n    return fromMissing(serializer, result);\n  }\n  return fail(0x1c42, 'invalid batch get response', { result });\n}\n\nexport function fromWatchChange(\n  serializer: JsonProtoSerializer,\n  change: ProtoListenResponse\n): WatchChange {\n  let watchChange: WatchChange;\n  if ('targetChange' in change) {\n    assertPresent(change.targetChange, 'targetChange');\n    // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n    // if unset\n    const state = fromWatchTargetChangeState(\n      change.targetChange.targetChangeType || 'NO_CHANGE'\n    );\n    const targetIds: RemoteTargetId[] = (change.targetChange.targetIds ||\n      []) as RemoteTargetId[];\n\n    const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n    const causeProto = change.targetChange!.cause;\n    const cause = causeProto && fromRpcStatus(causeProto);\n    watchChange = new WatchTargetChange(\n      state,\n      targetIds,\n      resumeToken,\n      cause || null\n    );\n  } else if ('documentChange' in change) {\n    assertPresent(change.documentChange, 'documentChange');\n    const entityChange = change.documentChange;\n    assertPresent(entityChange.document, 'documentChange.name');\n    assertPresent(entityChange.document.name, 'documentChange.document.name');\n    assertPresent(\n      entityChange.document.updateTime,\n      'documentChange.document.updateTime'\n    );\n    const key = fromName(serializer, entityChange.document.name);\n    const version = fromVersion(entityChange.document.updateTime);\n    const createTime = entityChange.document.createTime\n      ? fromVersion(entityChange.document.createTime)\n      : SnapshotVersion.min();\n    const data = new ObjectValue({\n      mapValue: { fields: entityChange.document.fields }\n    });\n    const doc = MutableDocument.newFoundDocument(\n      key,\n      version,\n      createTime,\n      data\n    );\n    const updatedTargetIds = (entityChange.targetIds || []) as RemoteTargetId[];\n    const removedTargetIds = (entityChange.removedTargetIds ||\n      []) as RemoteTargetId[];\n    watchChange = new DocumentWatchChange(\n      updatedTargetIds,\n      removedTargetIds,\n      doc.key,\n      doc\n    );\n  } else if ('documentDelete' in change) {\n    assertPresent(change.documentDelete, 'documentDelete');\n    const docDelete = change.documentDelete;\n    assertPresent(docDelete.document, 'documentDelete.document');\n    const key = fromName(serializer, docDelete.document);\n    const version = docDelete.readTime\n      ? fromVersion(docDelete.readTime)\n      : SnapshotVersion.min();\n    const doc = MutableDocument.newNoDocument(key, version);\n    const removedTargetIds = (docDelete.removedTargetIds ||\n      []) as RemoteTargetId[];\n    watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n  } else if ('documentRemove' in change) {\n    assertPresent(change.documentRemove, 'documentRemove');\n    const docRemove = change.documentRemove;\n    assertPresent(docRemove.document, 'documentRemove');\n    const key = fromName(serializer, docRemove.document);\n    const removedTargetIds = (docRemove.removedTargetIds ||\n      []) as RemoteTargetId[];\n    watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n  } else if ('filter' in change) {\n    // TODO(dimond): implement existence filter parsing with strategy.\n    assertPresent(change.filter, 'filter');\n    const filter = change.filter;\n    assertPresent(filter.targetId, 'filter.targetId');\n    const { count = 0, unchangedNames } = filter;\n    const existenceFilter = new ExistenceFilter(count, unchangedNames);\n    const targetId = filter.targetId as RemoteTargetId;\n    watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n  } else {\n    return fail(0x2d51, 'Unknown change type', { change });\n  }\n  return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n  state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n  if (state === 'NO_CHANGE') {\n    return WatchTargetChangeState.NoChange;\n  } else if (state === 'ADD') {\n    return WatchTargetChangeState.Added;\n  } else if (state === 'REMOVE') {\n    return WatchTargetChangeState.Removed;\n  } else if (state === 'CURRENT') {\n    return WatchTargetChangeState.Current;\n  } else if (state === 'RESET') {\n    return WatchTargetChangeState.Reset;\n  } else {\n    return fail(0x9991, 'Got unexpected TargetChange.state', { state });\n  }\n}\n\nexport function versionFromListenResponse(\n  change: ProtoListenResponse\n): SnapshotVersion {\n  // We have only reached a consistent snapshot for the entire stream if there\n  // is a read_time set and it applies to all targets (i.e. the list of\n  // targets is empty). The backend is guaranteed to send such responses.\n  if (!('targetChange' in change)) {\n    return SnapshotVersion.min();\n  }\n  const targetChange = change.targetChange!;\n  if (targetChange.targetIds && targetChange.targetIds.length) {\n    return SnapshotVersion.min();\n  }\n  if (!targetChange.readTime) {\n    return SnapshotVersion.min();\n  }\n  return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n  serializer: JsonProtoSerializer,\n  mutation: Mutation\n): ProtoWrite {\n  let result: ProtoWrite;\n  if (mutation instanceof SetMutation) {\n    result = {\n      update: toMutationDocument(serializer, mutation.key, mutation.value)\n    };\n  } else if (mutation instanceof DeleteMutation) {\n    result = { delete: toName(serializer, mutation.key) };\n  } else if (mutation instanceof PatchMutation) {\n    result = {\n      update: toMutationDocument(serializer, mutation.key, mutation.data),\n      updateMask: toDocumentMask(mutation.fieldMask)\n    };\n  } else if (mutation instanceof VerifyMutation) {\n    result = {\n      verify: toName(serializer, mutation.key)\n    };\n  } else {\n    return fail(0x40d7, 'Unknown mutation type', {\n      mutationType: mutation.type\n    });\n  }\n\n  if (mutation.fieldTransforms.length > 0) {\n    result.updateTransforms = mutation.fieldTransforms.map(transform =>\n      toFieldTransform(serializer, transform)\n    );\n  }\n\n  if (!mutation.precondition.isNone) {\n    result.currentDocument = toPrecondition(serializer, mutation.precondition);\n  }\n\n  return result;\n}\n\nexport function fromMutation(\n  serializer: JsonProtoSerializer,\n  proto: ProtoWrite\n): Mutation {\n  const precondition = proto.currentDocument\n    ? fromPrecondition(proto.currentDocument)\n    : Precondition.none();\n\n  const fieldTransforms = proto.updateTransforms\n    ? proto.updateTransforms.map(transform =>\n        fromFieldTransform(serializer, transform)\n      )\n    : [];\n\n  if (proto.update) {\n    assertPresent(proto.update.name, 'name');\n    const key = fromName(serializer, proto.update.name);\n    const value = new ObjectValue({\n      mapValue: { fields: proto.update.fields }\n    });\n\n    if (proto.updateMask) {\n      const fieldMask = fromDocumentMask(proto.updateMask);\n      return new PatchMutation(\n        key,\n        value,\n        fieldMask,\n        precondition,\n        fieldTransforms\n      );\n    } else {\n      return new SetMutation(key, value, precondition, fieldTransforms);\n    }\n  } else if (proto.delete) {\n    const key = fromName(serializer, proto.delete);\n    return new DeleteMutation(key, precondition);\n  } else if (proto.verify) {\n    const key = fromName(serializer, proto.verify);\n    return new VerifyMutation(key, precondition);\n  } else {\n    return fail(0x05b7, 'unknown mutation proto', { proto });\n  }\n}\n\nfunction toPrecondition(\n  serializer: JsonProtoSerializer,\n  precondition: Precondition\n): ProtoPrecondition {\n  debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n  if (precondition.updateTime !== undefined) {\n    return {\n      updateTime: toVersion(serializer, precondition.updateTime)\n    };\n  } else if (precondition.exists !== undefined) {\n    return { exists: precondition.exists };\n  } else {\n    return fail(0x6b69, 'Unknown precondition');\n  }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n  if (precondition.updateTime !== undefined) {\n    return Precondition.updateTime(fromVersion(precondition.updateTime));\n  } else if (precondition.exists !== undefined) {\n    return Precondition.exists(precondition.exists);\n  } else {\n    return Precondition.none();\n  }\n}\n\nfunction fromWriteResult(\n  proto: ProtoWriteResult,\n  commitTime: ProtoTimestamp\n): MutationResult {\n  // NOTE: Deletes don't have an updateTime.\n  let version = proto.updateTime\n    ? fromVersion(proto.updateTime)\n    : fromVersion(commitTime);\n\n  if (version.isEqual(SnapshotVersion.min())) {\n    // The Firestore Emulator currently returns an update time of 0 for\n    // deletes of non-existing documents (rather than null). This breaks the\n    // test \"get deleted doc while offline with source=cache\" as NoDocuments\n    // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n    // TODO(#2149): Remove this when Emulator is fixed\n    version = fromVersion(commitTime);\n  }\n\n  return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n  protos: ProtoWriteResult[] | undefined,\n  commitTime?: ProtoTimestamp\n): MutationResult[] {\n  if (protos && protos.length > 0) {\n    hardAssert(\n      commitTime !== undefined,\n      0x3811,\n      'Received a write result without a commit time'\n    );\n    return protos.map(proto => fromWriteResult(proto, commitTime));\n  } else {\n    return [];\n  }\n}\n\nfunction toFieldTransform(\n  serializer: JsonProtoSerializer,\n  fieldTransform: FieldTransform\n): ProtoFieldTransform {\n  const transform = fieldTransform.transform;\n  if (transform instanceof ServerTimestampTransform) {\n    return {\n      fieldPath: fieldTransform.field.canonicalString(),\n      setToServerValue: 'REQUEST_TIME'\n    };\n  } else if (transform instanceof ArrayUnionTransformOperation) {\n    return {\n      fieldPath: fieldTransform.field.canonicalString(),\n      appendMissingElements: {\n        values: transform.elements\n      }\n    };\n  } else if (transform instanceof ArrayRemoveTransformOperation) {\n    return {\n      fieldPath: fieldTransform.field.canonicalString(),\n      removeAllFromArray: {\n        values: transform.elements\n      }\n    };\n  } else if (transform instanceof NumericIncrementTransformOperation) {\n    return {\n      fieldPath: fieldTransform.field.canonicalString(),\n      increment: transform.operand\n    };\n  } else {\n    throw fail(0x51c2, 'Unknown transform', {\n      transform: fieldTransform.transform\n    });\n  }\n}\n\nfunction fromFieldTransform(\n  serializer: JsonProtoSerializer,\n  proto: ProtoFieldTransform\n): FieldTransform {\n  let transform: TransformOperation | null = null;\n  if ('setToServerValue' in proto) {\n    hardAssert(\n      proto.setToServerValue === 'REQUEST_TIME',\n      0x40f6,\n      'Unknown server value transform proto',\n      { proto }\n    );\n    transform = new ServerTimestampTransform();\n  } else if ('appendMissingElements' in proto) {\n    const values = proto.appendMissingElements!.values || [];\n    transform = new ArrayUnionTransformOperation(values);\n  } else if ('removeAllFromArray' in proto) {\n    const values = proto.removeAllFromArray!.values || [];\n    transform = new ArrayRemoveTransformOperation(values);\n  } else if ('increment' in proto) {\n    transform = new NumericIncrementTransformOperation(\n      serializer,\n      proto.increment!\n    );\n  } else {\n    fail(0x40c8, 'Unknown transform proto', { proto });\n  }\n  const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n  return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n  serializer: JsonProtoSerializer,\n  target: Target\n): ProtoDocumentsTarget {\n  return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n  documentsTarget: ProtoDocumentsTarget\n): Target {\n  const count = documentsTarget.documents!.length;\n  hardAssert(\n    count === 1,\n    0x07ae,\n    'DocumentsTarget contained other than 1 document',\n    {\n      count\n    }\n  );\n  const name = documentsTarget.documents![0];\n  return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n  serializer: JsonProtoSerializer,\n  target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n  // Dissect the path into parent, collectionId, and optional key filter.\n  const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n  const path = target.path;\n  let parent: ResourcePath;\n  if (target.collectionGroup !== null) {\n    debugAssert(\n      path.length % 2 === 0,\n      'Collection Group queries should be within a document path or root.'\n    );\n    parent = path;\n    queryTarget.structuredQuery!.from = [\n      {\n        collectionId: target.collectionGroup,\n        allDescendants: true\n      }\n    ];\n  } else {\n    debugAssert(\n      path.length % 2 !== 0,\n      'Document queries with filters are not supported.'\n    );\n    parent = path.popLast();\n    queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n  }\n  queryTarget.parent = toQueryPath(serializer, parent);\n\n  const where = toFilters(target.filters);\n  if (where) {\n    queryTarget.structuredQuery!.where = where;\n  }\n\n  const orderBy = toOrder(target.orderBy);\n  if (orderBy) {\n    queryTarget.structuredQuery!.orderBy = orderBy;\n  }\n\n  const limit = toInt32Proto(serializer, target.limit);\n  if (limit !== null) {\n    queryTarget.structuredQuery!.limit = limit;\n  }\n\n  if (target.startAt) {\n    queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n  }\n  if (target.endAt) {\n    queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n  }\n\n  return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n  serializer: JsonProtoSerializer,\n  target: Target,\n  aggregates: Aggregate[],\n  skipAliasing?: boolean\n): {\n  request: ProtoRunAggregationQueryRequest;\n  aliasMap: Record<string, string>;\n  parent: ResourcePath;\n} {\n  const { queryTarget, parent } = toQueryTarget(serializer, target);\n  const aliasMap: Record<string, string> = {};\n\n  const aggregations: ProtoAggregation[] = [];\n  let aggregationNum = 0;\n\n  aggregates.forEach(aggregate => {\n    // Map all client-side aliases to a unique short-form\n    // alias. This avoids issues with client-side aliases that\n    // exceed the 1500-byte string size limit.\n    const serverAlias = skipAliasing\n      ? aggregate.alias\n      : `aggregate_${aggregationNum++}`;\n    aliasMap[serverAlias] = aggregate.alias;\n\n    if (aggregate.aggregateType === 'count') {\n      aggregations.push({\n        alias: serverAlias,\n        count: {}\n      });\n    } else if (aggregate.aggregateType === 'avg') {\n      aggregations.push({\n        alias: serverAlias,\n        avg: {\n          field: toFieldPathReference(aggregate.fieldPath!)\n        }\n      });\n    } else if (aggregate.aggregateType === 'sum') {\n      aggregations.push({\n        alias: serverAlias,\n        sum: {\n          field: toFieldPathReference(aggregate.fieldPath!)\n        }\n      });\n    }\n  });\n\n  return {\n    request: {\n      structuredAggregationQuery: {\n        aggregations,\n        structuredQuery: queryTarget.structuredQuery\n      },\n      parent: queryTarget.parent\n    },\n    aliasMap,\n    parent\n  };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n  let path = fromQueryPath(target.parent!);\n\n  const query = target.structuredQuery!;\n  const fromCount = query.from ? query.from.length : 0;\n  let collectionGroup: string | null = null;\n  if (fromCount > 0) {\n    hardAssert(\n      fromCount === 1,\n      0xfe26,\n      'StructuredQuery.from with more than one collection is not supported.'\n    );\n    const from = query.from![0];\n    if (from.allDescendants) {\n      collectionGroup = from.collectionId!;\n    } else {\n      path = path.child(from.collectionId!);\n    }\n  }\n\n  let filterBy: Filter[] = [];\n  if (query.where) {\n    filterBy = fromFilters(query.where);\n  }\n\n  let orderBy: OrderBy[] = [];\n  if (query.orderBy) {\n    orderBy = fromOrder(query.orderBy);\n  }\n\n  let limit: number | null = null;\n  if (query.limit) {\n    limit = fromInt32Proto(query.limit);\n  }\n\n  let startAt: Bound | null = null;\n  if (query.startAt) {\n    startAt = fromStartAtCursor(query.startAt);\n  }\n\n  let endAt: Bound | null = null;\n  if (query.endAt) {\n    endAt = fromEndAtCursor(query.endAt);\n  }\n\n  return newQuery(\n    path,\n    collectionGroup,\n    orderBy,\n    filterBy,\n    limit,\n    LimitType.First,\n    startAt,\n    endAt\n  );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n  return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n  serializer: JsonProtoSerializer,\n  targetData: TargetData<number>\n): ProtoApiClientObjectMap<string> | null {\n  const value = toLabel(targetData.purpose);\n  if (value == null) {\n    return null;\n  } else {\n    return {\n      'goog-listen-tags': value\n    };\n  }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n  switch (purpose) {\n    case TargetPurpose.Listen:\n      return null;\n    case TargetPurpose.ExistenceFilterMismatch:\n      return 'existence-filter-mismatch';\n    case TargetPurpose.ExistenceFilterMismatchBloom:\n      return 'existence-filter-mismatch-bloom';\n    case TargetPurpose.LimboResolution:\n      return 'limbo-document';\n    default:\n      return fail(0x713b, 'Unrecognized query purpose', { purpose });\n  }\n}\n\nexport function toTarget(\n  serializer: JsonProtoSerializer,\n  targetData: TargetData<number>\n): ProtoTarget {\n  let result: ProtoTarget;\n  const target = targetData.target;\n\n  if (targetIsDocumentTarget(target)) {\n    result = { documents: toDocumentsTarget(serializer, target) };\n  } else {\n    result = { query: toQueryTarget(serializer, target).queryTarget };\n  }\n\n  result.targetId = targetData.targetId;\n\n  if (targetData.resumeToken.approximateByteSize() > 0) {\n    result.resumeToken = toBytes(serializer, targetData.resumeToken);\n    const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n    if (expectedCount !== null) {\n      result.expectedCount = expectedCount;\n    }\n  } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n    // TODO(wuandy): Consider removing above check because it is most likely true.\n    // Right now, many tests depend on this behaviour though (leaving min() out\n    // of serialization).\n    result.readTime = toTimestamp(\n      serializer,\n      targetData.snapshotVersion.toTimestamp()\n    );\n    const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n    if (expectedCount !== null) {\n      result.expectedCount = expectedCount;\n    }\n  }\n\n  return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n  if (filters.length === 0) {\n    return;\n  }\n\n  return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n  const result = fromFilter(filter);\n\n  if (\n    result instanceof CompositeFilter &&\n    compositeFilterIsFlatConjunction(result)\n  ) {\n    return result.getFilters();\n  }\n\n  return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n  if (filter.unaryFilter !== undefined) {\n    return fromUnaryFilter(filter);\n  } else if (filter.fieldFilter !== undefined) {\n    return fromFieldFilter(filter);\n  } else if (filter.compositeFilter !== undefined) {\n    return fromCompositeFilter(filter);\n  } else {\n    return fail(0x7591, 'Unknown filter', { filter });\n  }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n  if (orderBys.length === 0) {\n    return;\n  }\n  return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n  return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n  return {\n    before: cursor.inclusive,\n    values: cursor.position\n  };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n  return {\n    before: !cursor.inclusive,\n    values: cursor.position\n  };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n  const inclusive = !!cursor.before;\n  const position = cursor.values || [];\n  return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n  const inclusive = !cursor.before;\n  const position = cursor.values || [];\n  return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n  return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n  dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n  switch (dir) {\n    case 'ASCENDING':\n      return Direction.ASCENDING;\n    case 'DESCENDING':\n      return Direction.DESCENDING;\n    default:\n      return undefined;\n  }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n  return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n  op: CompositeOperator\n): ProtoCompositeFilterOp {\n  return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n  switch (op) {\n    case 'EQUAL':\n      return Operator.EQUAL;\n    case 'NOT_EQUAL':\n      return Operator.NOT_EQUAL;\n    case 'GREATER_THAN':\n      return Operator.GREATER_THAN;\n    case 'GREATER_THAN_OR_EQUAL':\n      return Operator.GREATER_THAN_OR_EQUAL;\n    case 'LESS_THAN':\n      return Operator.LESS_THAN;\n    case 'LESS_THAN_OR_EQUAL':\n      return Operator.LESS_THAN_OR_EQUAL;\n    case 'ARRAY_CONTAINS':\n      return Operator.ARRAY_CONTAINS;\n    case 'IN':\n      return Operator.IN;\n    case 'NOT_IN':\n      return Operator.NOT_IN;\n    case 'ARRAY_CONTAINS_ANY':\n      return Operator.ARRAY_CONTAINS_ANY;\n    case 'OPERATOR_UNSPECIFIED':\n      return fail(0xe2fe, 'Unspecified operator');\n    default:\n      return fail(0xc54a, 'Unknown operator');\n  }\n}\n\nexport function fromCompositeOperatorName(\n  op: ProtoCompositeFilterOp\n): CompositeOperator {\n  switch (op) {\n    case 'AND':\n      return CompositeOperator.AND;\n    case 'OR':\n      return CompositeOperator.OR;\n    default:\n      return fail(0x0402, 'Unknown operator');\n  }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n  return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n  fieldReference: ProtoFieldReference\n): FieldPath {\n  return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n  return {\n    field: toFieldPathReference(orderBy.field),\n    direction: toDirection(orderBy.dir)\n  };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n  return new OrderBy(\n    fromFieldPathReference(orderBy.field!),\n    fromDirection(orderBy.direction)\n  );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n  if (filter instanceof FieldFilter) {\n    return toUnaryOrFieldFilter(filter);\n  } else if (filter instanceof CompositeFilter) {\n    return toCompositeFilter(filter);\n  } else {\n    return fail(0xd65d, 'Unrecognized filter type', { filter });\n  }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n  const protos = filter.getFilters().map(filter => toFilter(filter));\n\n  if (protos.length === 1) {\n    return protos[0];\n  }\n\n  return {\n    compositeFilter: {\n      op: toCompositeOperatorName(filter.op),\n      filters: protos\n    }\n  };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n  if (filter.op === Operator.EQUAL) {\n    if (isNanValue(filter.value)) {\n      return {\n        unaryFilter: {\n          field: toFieldPathReference(filter.field),\n          op: 'IS_NAN'\n        }\n      };\n    } else if (isNullValue(filter.value)) {\n      return {\n        unaryFilter: {\n          field: toFieldPathReference(filter.field),\n          op: 'IS_NULL'\n        }\n      };\n    }\n  } else if (filter.op === Operator.NOT_EQUAL) {\n    if (isNanValue(filter.value)) {\n      return {\n        unaryFilter: {\n          field: toFieldPathReference(filter.field),\n          op: 'IS_NOT_NAN'\n        }\n      };\n    } else if (isNullValue(filter.value)) {\n      return {\n        unaryFilter: {\n          field: toFieldPathReference(filter.field),\n          op: 'IS_NOT_NULL'\n        }\n      };\n    }\n  }\n  return {\n    fieldFilter: {\n      field: toFieldPathReference(filter.field),\n      op: toOperatorName(filter.op),\n      value: filter.value\n    }\n  };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n  switch (filter.unaryFilter!.op!) {\n    case 'IS_NAN':\n      const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n      return FieldFilter.create(nanField, Operator.EQUAL, {\n        doubleValue: NaN\n      });\n    case 'IS_NULL':\n      const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n      return FieldFilter.create(nullField, Operator.EQUAL, {\n        nullValue: 'NULL_VALUE'\n      });\n    case 'IS_NOT_NAN':\n      const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n      return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n        doubleValue: NaN\n      });\n    case 'IS_NOT_NULL':\n      const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n      return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n        nullValue: 'NULL_VALUE'\n      });\n    case 'OPERATOR_UNSPECIFIED':\n      return fail(0xef81, 'Unspecified filter');\n    default:\n      return fail(0xed36, 'Unknown filter');\n  }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n  return FieldFilter.create(\n    fromFieldPathReference(filter.fieldFilter!.field!),\n    fromOperatorName(filter.fieldFilter!.op!),\n    filter.fieldFilter!.value!\n  );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n  return CompositeFilter.create(\n    filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n    fromCompositeOperatorName(filter.compositeFilter!.op!)\n  );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n  const canonicalFields: string[] = [];\n  fieldMask.fields.forEach(field =>\n    canonicalFields.push(field.canonicalString())\n  );\n  return {\n    fieldPaths: canonicalFields\n  };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n  const paths = proto.fieldPaths || [];\n  return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n  // Resource names have at least 4 components (project ID, database ID)\n  return (\n    path.length >= 4 &&\n    path.get(0) === 'projects' &&\n    path.get(2) === 'databases'\n  );\n}\n\nexport interface ProtoSerializable<ProtoType> {\n  _toProto(serializer: JsonProtoSerializer): ProtoType;\n}\n\nexport interface ProtoValueSerializable extends ProtoSerializable<ProtoValue> {\n  // Supports runtime identification of the ProtoSerializable<ProtoValue> type.\n  _protoValueType: 'ProtoValue';\n}\n\nexport function isProtoValueSerializable(\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  value: any\n): value is ProtoValueSerializable {\n  return (\n    !!value &&\n    typeof value._toProto === 'function' &&\n    value._protoValueType === 'ProtoValue'\n  );\n}\n\nexport function toMapValue(\n  serializer: JsonProtoSerializer,\n  input: Map<string, ProtoSerializable<ProtoValue>>\n): ProtoValue {\n  const map: ProtoMapValue = { fields: {} };\n  input.forEach((exp: ProtoSerializable<ProtoValue>, key: string) => {\n    if (typeof key !== 'string') {\n      throw new Error(`Cannot encode map with non-string key: ${key}`);\n    }\n\n    map.fields![key] = exp._toProto(serializer)!;\n  });\n  return {\n    mapValue: map\n  };\n}\n\nexport function toNullValue(value: null): ProtoValue {\n  return { nullValue: 'NULL_VALUE' };\n}\n\nexport function toBooleanValue(value: boolean): ProtoValue {\n  return { booleanValue: value };\n}\n\nexport function toStringValue(value: string): ProtoValue {\n  return { stringValue: value };\n}\n\nexport function toPipelineValue(value: ProtoPipeline): ProtoValue {\n  return { pipelineValue: value };\n}\n\nexport function dateToTimestampValue(\n  serializer: JsonProtoSerializer,\n  value: Date\n): ProtoValue {\n  const timestamp = Timestamp.fromDate(value);\n  return {\n    timestampValue: toTimestamp(serializer, timestamp)\n  };\n}\n\nexport function timestampToTimestampValue(\n  serializer: JsonProtoSerializer,\n  value: Timestamp\n): ProtoValue {\n  // Firestore backend truncates precision down to microseconds. To ensure\n  // offline mode works the same in regards to truncation, perform the\n  // truncation immediately without waiting for the backend to do that.\n  const timestamp = new Timestamp(\n    value.seconds,\n    Math.floor(value.nanoseconds / 1000) * 1000\n  );\n  return {\n    timestampValue: toTimestamp(serializer, timestamp)\n  };\n}\n\nexport function toGeoPointValue(value: GeoPoint): ProtoValue {\n  return {\n    geoPointValue: {\n      latitude: value.latitude,\n      longitude: value.longitude\n    }\n  };\n}\n\nexport function toBytesValue(\n  serializer: JsonProtoSerializer,\n  value: Bytes\n): ProtoValue {\n  return { bytesValue: toBytes(serializer, value._byteString) };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n  return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { StructuredPipeline } from '../core/structured_pipeline';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport { PipelineStreamElement } from '../model/pipeline_stream_element';\nimport {\n  ApiClientObjectMap,\n  BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n  BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n  RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n  RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n  RunQueryRequest as ProtoRunQueryRequest,\n  RunQueryResponse as ProtoRunQueryResponse,\n  ExecutePipelineRequest as ProtoExecutePipelineRequest,\n  ExecutePipelineResponse as ProtoExecutePipelineResponse,\n  Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n  PersistentListenStream,\n  PersistentWriteStream,\n  WatchStreamListener,\n  WriteStreamListener\n} from './persistent_stream';\nimport {\n  fromDocument,\n  fromBatchGetDocumentsResponse,\n  JsonProtoSerializer,\n  toMutation,\n  toName,\n  toQueryTarget,\n  toResourcePath,\n  toRunAggregationQueryRequest,\n  fromPipelineResponse,\n  getEncodedDatabaseId\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n  abstract terminate(): void;\n  abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n  terminated = false;\n\n  constructor(\n    readonly authCredentials: CredentialsProvider<User>,\n    readonly appCheckCredentials: CredentialsProvider<string>,\n    readonly connection: Connection,\n    readonly serializer: JsonProtoSerializer\n  ) {\n    super();\n  }\n\n  verifyInitialized(): void {\n    debugAssert(!!this.connection, 'Datastore.start() not called');\n    if (this.terminated) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'The client has already been terminated.'\n      );\n    }\n  }\n\n  /** Invokes the provided RPC with auth and AppCheck tokens. */\n  invokeRPC<Req, Resp>(\n    rpcName: string,\n    databaseId: DatabaseId,\n    resourcePath: ResourcePath,\n    request: Req\n  ): Promise<Resp> {\n    this.verifyInitialized();\n    return Promise.all([\n      this.authCredentials.getToken(),\n      this.appCheckCredentials.getToken()\n    ])\n      .then(([authToken, appCheckToken]) => {\n        return this.connection.invokeRPC<Req, Resp>(\n          rpcName,\n          toResourcePath(databaseId, resourcePath),\n          request,\n          authToken,\n          appCheckToken\n        );\n      })\n      .catch((error: FirestoreError) => {\n        if (error.name === 'FirebaseError') {\n          if (error.code === Code.UNAUTHENTICATED) {\n            this.authCredentials.invalidateToken();\n            this.appCheckCredentials.invalidateToken();\n          }\n          throw error;\n        } else {\n          throw new FirestoreError(Code.UNKNOWN, error.toString());\n        }\n      });\n  }\n\n  /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n  invokeStreamingRPC<Req, Resp>(\n    rpcName: string,\n    databaseId: DatabaseId,\n    resourcePath: ResourcePath,\n    request: Req,\n    expectedResponseCount?: number\n  ): Promise<Resp[]> {\n    this.verifyInitialized();\n    return Promise.all([\n      this.authCredentials.getToken(),\n      this.appCheckCredentials.getToken()\n    ])\n      .then(([authToken, appCheckToken]) => {\n        return this.connection.invokeStreamingRPC<Req, Resp>(\n          rpcName,\n          toResourcePath(databaseId, resourcePath),\n          request,\n          authToken,\n          appCheckToken,\n          expectedResponseCount\n        );\n      })\n      .catch((error: FirestoreError) => {\n        if (error.name === 'FirebaseError') {\n          if (error.code === Code.UNAUTHENTICATED) {\n            this.authCredentials.invalidateToken();\n            this.appCheckCredentials.invalidateToken();\n          }\n          throw error;\n        } else {\n          throw new FirestoreError(Code.UNKNOWN, error.toString());\n        }\n      });\n  }\n\n  terminate(): void {\n    this.terminated = true;\n    this.connection.terminate();\n  }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n  authCredentials: CredentialsProvider<User>,\n  appCheckCredentials: CredentialsProvider<string>,\n  connection: Connection,\n  serializer: JsonProtoSerializer\n): Datastore {\n  return new DatastoreImpl(\n    authCredentials,\n    appCheckCredentials,\n    connection,\n    serializer\n  );\n}\n\nexport async function invokeCommitRpc(\n  datastore: Datastore,\n  mutations: Mutation[]\n): Promise<void> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const request = {\n    writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n  };\n  await datastoreImpl.invokeRPC(\n    'Commit',\n    datastoreImpl.serializer.databaseId,\n    ResourcePath.emptyPath(),\n    request\n  );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n  datastore: Datastore,\n  keys: DocumentKey[]\n): Promise<Document[]> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const request = {\n    documents: keys.map(k => toName(datastoreImpl.serializer, k))\n  };\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoBatchGetDocumentsRequest,\n    ProtoBatchGetDocumentsResponse\n  >(\n    'BatchGetDocuments',\n    datastoreImpl.serializer.databaseId,\n    ResourcePath.emptyPath(),\n    request,\n    keys.length\n  );\n\n  const docs = new Map<string, Document>();\n  response.forEach(proto => {\n    const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n    docs.set(doc.key.toString(), doc);\n  });\n  const result: Document[] = [];\n  keys.forEach(key => {\n    const doc = docs.get(key.toString());\n    hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n      key\n    });\n    result.push(doc);\n  });\n  return result;\n}\n\nexport async function invokeExecutePipeline(\n  datastore: Datastore,\n  structuredPipeline: StructuredPipeline\n): Promise<PipelineStreamElement[]> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const executePipelineRequest: ProtoExecutePipelineRequest = {\n    database: getEncodedDatabaseId(datastoreImpl.serializer),\n    structuredPipeline: structuredPipeline._toProto(datastoreImpl.serializer)\n  };\n\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoExecutePipelineRequest,\n    ProtoExecutePipelineResponse\n  >(\n    'ExecutePipeline',\n    datastoreImpl.serializer.databaseId,\n    ResourcePath.emptyPath(),\n    executePipelineRequest\n  );\n\n  const result: PipelineStreamElement[] = [];\n  response.forEach(proto => {\n    if (!proto.results || proto.results!.length === 0) {\n      result.push(fromPipelineResponse(datastoreImpl.serializer, proto));\n    } else {\n      return proto.results!.forEach(document =>\n        result.push(\n          fromPipelineResponse(datastoreImpl.serializer, proto, document)\n        )\n      );\n    }\n  });\n\n  return result;\n}\n\nexport async function invokeRunQueryRpc(\n  datastore: Datastore,\n  query: Query\n): Promise<Document[]> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const { queryTarget, parent } = toQueryTarget(\n    datastoreImpl.serializer,\n    queryToTarget(query)\n  );\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoRunQueryRequest,\n    ProtoRunQueryResponse\n  >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n    structuredQuery: queryTarget.structuredQuery\n  });\n  return (\n    response\n      // Omit RunQueryResponses that only contain readTimes.\n      .filter(proto => !!proto.document)\n      .map(proto =>\n        fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n      )\n  );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n  datastore: Datastore,\n  query: Query,\n  aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n    datastoreImpl.serializer,\n    queryToAggregateTarget(query),\n    aggregates\n  );\n\n  if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n    delete request.parent;\n  }\n  const response = await datastoreImpl.invokeStreamingRPC<\n    ProtoRunAggregationQueryRequest,\n    ProtoRunAggregationQueryResponse\n  >(\n    'RunAggregationQuery',\n    datastoreImpl.serializer.databaseId,\n    parent,\n    request,\n    /*expectedResponseCount=*/ 1\n  );\n\n  // Omit RunAggregationQueryResponse that only contain readTimes.\n  const filteredResult = response.filter(proto => !!proto.result);\n\n  hardAssert(\n    filteredResult.length === 1,\n    0xfcd7,\n    'Aggregation fields are missing from result.'\n  );\n  debugAssert(\n    !isNullOrUndefined(filteredResult[0].result),\n    'aggregationQueryResponse.result'\n  );\n  debugAssert(\n    !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n    'aggregationQueryResponse.result.aggregateFields'\n  );\n\n  // Remap the short-form aliases that were sent to the server\n  // to the client-side aliases. Users will access the results\n  // using the client-side alias.\n  const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n  const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n    ApiClientObjectMap<Value>\n  >((accumulator, key) => {\n    debugAssert(\n      !isNullOrUndefined(aliasMap[key]),\n      `'${key}' not present in aliasMap result`\n    );\n    accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n    return accumulator;\n  }, {});\n\n  return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n  datastore: Datastore,\n  queue: AsyncQueue,\n  listener: WriteStreamListener\n): PersistentWriteStream {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  datastoreImpl.verifyInitialized();\n  return new PersistentWriteStream(\n    queue,\n    datastoreImpl.connection,\n    datastoreImpl.authCredentials,\n    datastoreImpl.appCheckCredentials,\n    datastoreImpl.serializer,\n    listener\n  );\n}\n\nexport function newPersistentWatchStream(\n  datastore: Datastore,\n  queue: AsyncQueue,\n  listener: WatchStreamListener\n): PersistentListenStream {\n  const datastoreImpl = debugCast(datastore, DatastoreImpl);\n  datastoreImpl.verifyInitialized();\n  return new PersistentListenStream(\n    queue,\n    datastoreImpl.connection,\n    datastoreImpl.authCredentials,\n    datastoreImpl.appCheckCredentials,\n    datastoreImpl.serializer,\n    listener\n  );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n  _authCredentials: CredentialsProvider<User>;\n  _appCheckCredentials: CredentialsProvider<string>;\n  _persistenceKey: string;\n  _databaseId: DatabaseId;\n  _terminated: boolean;\n\n  _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map<FirestoreService, Datastore>();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n  if (firestore._terminated) {\n    throw new FirestoreError(\n      Code.FAILED_PRECONDITION,\n      'The client has already been terminated.'\n    );\n  }\n  if (!datastoreInstances.has(firestore)) {\n    logDebug(LOG_TAG, 'Initializing Datastore');\n    const databaseInfo = makeDatabaseInfo(\n      firestore._databaseId,\n      firestore.app.options.appId || '',\n      firestore._persistenceKey,\n      firestore.app.options.apiKey,\n      firestore._freezeSettings()\n    );\n    const connection = newConnection(databaseInfo);\n    const serializer = newSerializer(firestore._databaseId);\n    const datastore = newDatastore(\n      firestore._authCredentials,\n      firestore._appCheckCredentials,\n      connection,\n      serializer\n    );\n\n    datastoreInstances.set(firestore, datastore);\n  }\n  return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n  const datastore = datastoreInstances.get(firestore);\n  if (datastore) {\n    logDebug(LOG_TAG, 'Removing Datastore');\n    datastoreInstances.delete(firestore);\n    datastore.terminate();\n  }\n}\n\nexport function makeDatabaseInfo(\n  databaseId: DatabaseId,\n  appId: string,\n  persistenceKey: string,\n  apiKey: string | undefined,\n  settings: FirestoreSettingsImpl\n): DatabaseInfo {\n  return new DatabaseInfo(\n    databaseId,\n    appId,\n    persistenceKey,\n    settings.host,\n    settings.ssl,\n    settings.experimentalForceLongPolling,\n    settings.experimentalAutoDetectLongPolling,\n    cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n    settings.useFetchStreams,\n    settings.isUsingEmulator,\n    apiKey\n  );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap<TargetId, unknown>;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n  didRun: false,\n  sequenceNumbersCollected: 0,\n  targetsRemoved: 0,\n  documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n  private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n  private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n  static withCacheSize(cacheSize: number): LruParams {\n    return new LruParams(\n      cacheSize,\n      LruParams.DEFAULT_COLLECTION_PERCENTILE,\n      LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n    );\n  }\n\n  static readonly DEFAULT: LruParams = new LruParams(\n    LRU_DEFAULT_CACHE_SIZE_BYTES,\n    LruParams.DEFAULT_COLLECTION_PERCENTILE,\n    LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n  );\n\n  static readonly DISABLED: LruParams = new LruParams(\n    LRU_COLLECTION_DISABLED,\n    0,\n    0\n  );\n\n  constructor(\n    // When we attempt to collect, we will only do so if the cache size is greater than this\n    // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n    readonly cacheSizeCollectionThreshold: number,\n    // The percentage of sequence numbers that we will attempt to collect\n    readonly percentileToCollect: number,\n    // A cap on the total number of sequence numbers that will be collected. This prevents\n    // us from collecting a huge number of sequence numbers if the cache has grown very large.\n    readonly maximumSequenceNumbersToCollect: number\n  ) {}\n}\n\nexport interface LruGarbageCollector {\n  readonly params: LruParams;\n\n  collect(\n    txn: PersistenceTransaction,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<LruResults>;\n\n  /** Given a percentile of target to collect, returns the number of targets to collect. */\n  calculateTargetCount(\n    txn: PersistenceTransaction,\n    percentile: number\n  ): PersistencePromise<number>;\n\n  /** Returns the nth sequence number, counting in order from the smallest. */\n  nthSequenceNumber(\n    txn: PersistenceTransaction,\n    n: number\n  ): PersistencePromise<number>;\n\n  /**\n   * Removes documents that have a sequence number equal to or less than the\n   * upper bound and are not otherwise pinned.\n   */\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number>;\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n\n  /**\n   * Removes targets with a sequence number equal to or less than the given\n   * upper bound, and removes document associations with those targets.\n   */\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number>;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n  readonly didRun: boolean;\n  readonly sequenceNumbersCollected: number;\n  readonly targetsRemoved: number;\n  readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n  readonly garbageCollector: LruGarbageCollector;\n\n  /** Enumerates all the targets in the TargetCache. */\n  forEachTarget(\n    txn: PersistenceTransaction,\n    f: (target: TargetData) => void\n  ): PersistencePromise<void>;\n\n  getSequenceNumberCount(\n    txn: PersistenceTransaction\n  ): PersistencePromise<number>;\n\n  /**\n   * Enumerates sequence numbers for documents not associated with a target.\n   * Note that this may include duplicate sequence numbers.\n   */\n  forEachOrphanedDocumentSequenceNumber(\n    txn: PersistenceTransaction,\n    f: (sequenceNumber: ListenSequenceNumber) => void\n  ): PersistencePromise<void>;\n\n  /**\n   * Removes all targets that have a sequence number less than or equal to\n   * `upperBound`, and are not present in the `activeTargetIds` set.\n   *\n   * @returns the number of targets removed.\n   */\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number>;\n\n  /**\n   * Removes all unreferenced documents from the cache that have a sequence\n   * number less than or equal to the given `upperBound`.\n   *\n   * @returns the number of documents removed.\n   */\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number>;\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n  ExperimentalLongPollingOptions,\n  cloneLongPollingOptions,\n  longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n  LRU_COLLECTION_DISABLED,\n  LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n  /** The hostname to connect to. */\n  host?: string;\n\n  /** Whether to use SSL when connecting. */\n  ssl?: boolean;\n\n  /**\n   * Whether to skip nested properties that are set to `undefined` during\n   * object serialization. If set to `true`, these properties are skipped\n   * and not written to Firestore. If set to `false` or omitted, the SDK\n   * throws an exception when it encounters properties of type `undefined`.\n   */\n  ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n  // Can be a google-auth-library or gapi client.\n  credentials?: CredentialsSettings;\n  cacheSizeBytes?: number;\n  experimentalForceLongPolling?: boolean;\n  experimentalAutoDetectLongPolling?: boolean;\n  experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n  useFetchStreams?: boolean;\n  emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\n\n  localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n  /** The hostname to connect to. */\n  readonly host: string;\n\n  /** Whether to use SSL when connecting. */\n  readonly ssl: boolean;\n\n  readonly cacheSizeBytes: number;\n\n  readonly experimentalForceLongPolling: boolean;\n\n  readonly experimentalAutoDetectLongPolling: boolean;\n\n  readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n  readonly ignoreUndefinedProperties: boolean;\n\n  readonly useFetchStreams: boolean;\n  readonly localCache?: FirestoreLocalCache;\n\n  readonly isUsingEmulator: boolean;\n\n  // Can be a google-auth-library or gapi client.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  credentials?: any;\n\n  constructor(settings: PrivateSettings) {\n    if (settings.host === undefined) {\n      if (settings.ssl !== undefined) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          \"Can't provide ssl option if host option is not set\"\n        );\n      }\n      this.host = DEFAULT_HOST;\n      this.ssl = DEFAULT_SSL;\n    } else {\n      this.host = settings.host;\n      this.ssl = settings.ssl ?? DEFAULT_SSL;\n    }\n    this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n    this.credentials = settings.credentials;\n    this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n    this.localCache = settings.localCache;\n\n    if (settings.cacheSizeBytes === undefined) {\n      this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n    } else {\n      if (\n        settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n        settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n      ) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n        );\n      } else {\n        this.cacheSizeBytes = settings.cacheSizeBytes;\n      }\n    }\n\n    validateIsNotUsedTogether(\n      'experimentalForceLongPolling',\n      settings.experimentalForceLongPolling,\n      'experimentalAutoDetectLongPolling',\n      settings.experimentalAutoDetectLongPolling\n    );\n\n    this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n    if (this.experimentalForceLongPolling) {\n      this.experimentalAutoDetectLongPolling = false;\n    } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n      this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n    } else {\n      // For backwards compatibility, coerce the value to boolean even though\n      // the TypeScript compiler has narrowed the type to boolean already.\n      // noinspection PointlessBooleanExpressionJS\n      this.experimentalAutoDetectLongPolling =\n        !!settings.experimentalAutoDetectLongPolling;\n    }\n\n    this.experimentalLongPollingOptions = cloneLongPollingOptions(\n      settings.experimentalLongPollingOptions ?? {}\n    );\n    validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n    this.useFetchStreams = !!settings.useFetchStreams;\n  }\n\n  isEqual(other: FirestoreSettingsImpl): boolean {\n    return (\n      this.host === other.host &&\n      this.ssl === other.ssl &&\n      this.credentials === other.credentials &&\n      this.cacheSizeBytes === other.cacheSizeBytes &&\n      this.experimentalForceLongPolling ===\n        other.experimentalForceLongPolling &&\n      this.experimentalAutoDetectLongPolling ===\n        other.experimentalAutoDetectLongPolling &&\n      longPollingOptionsEqual(\n        this.experimentalLongPollingOptions,\n        other.experimentalLongPollingOptions\n      ) &&\n      this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n      this.useFetchStreams === other.useFetchStreams\n    );\n  }\n}\n\nfunction validateLongPollingOptions(\n  options: ExperimentalLongPollingOptions\n): void {\n  if (options.timeoutSeconds !== undefined) {\n    if (isNaN(options.timeoutSeconds)) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `invalid long polling timeout: ` +\n          `${options.timeoutSeconds} (must not be NaN)`\n      );\n    }\n    if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `invalid long polling timeout: ${options.timeoutSeconds} ` +\n          `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n      );\n    }\n    if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `invalid long polling timeout: ${options.timeoutSeconds} ` +\n          `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n      );\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n  ActiveTargets,\n  GC_DID_NOT_RUN,\n  LRU_COLLECTION_DISABLED,\n  LruDelegate,\n  LruGarbageCollector,\n  LruParams,\n  LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n  [aSequence, aIndex]: BufferEntry,\n  [bSequence, bIndex]: BufferEntry\n): number {\n  const seqCmp = primitiveComparator(aSequence, bSequence);\n  if (seqCmp === 0) {\n    // This order doesn't matter, but we can bias against churn by sorting\n    // entries created earlier as less than newer entries.\n    return primitiveComparator(aIndex, bIndex);\n  } else {\n    return seqCmp;\n  }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n  private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n    bufferEntryComparator\n  );\n\n  private previousIndex = 0;\n\n  constructor(private readonly maxElements: number) {}\n\n  private nextIndex(): number {\n    return ++this.previousIndex;\n  }\n\n  addElement(sequenceNumber: ListenSequenceNumber): void {\n    const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n    if (this.buffer.size < this.maxElements) {\n      this.buffer = this.buffer.add(entry);\n    } else {\n      const highestValue = this.buffer.last()!;\n      if (bufferEntryComparator(entry, highestValue) < 0) {\n        this.buffer = this.buffer.delete(highestValue).add(entry);\n      }\n    }\n  }\n\n  get maxValue(): ListenSequenceNumber {\n    // Guaranteed to be non-empty. If we decide we are not collecting any\n    // sequence numbers, nthSequenceNumber below short-circuits. If we have\n    // decided that we are collecting n sequence numbers, it's because n is some\n    // percentage of the existing sequence numbers. That means we should never\n    // be in a situation where we are collecting sequence numbers but don't\n    // actually have any.\n    return this.buffer.last()![0];\n  }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n  private gcTask: DelayedOperation<void> | null;\n\n  constructor(\n    private readonly garbageCollector: LruGarbageCollector,\n    private readonly asyncQueue: AsyncQueue,\n    private readonly localStore: LocalStore\n  ) {\n    this.gcTask = null;\n  }\n\n  start(): void {\n    debugAssert(\n      this.gcTask === null,\n      'Cannot start an already started LruScheduler'\n    );\n    if (\n      this.garbageCollector.params.cacheSizeCollectionThreshold !==\n      LRU_COLLECTION_DISABLED\n    ) {\n      this.scheduleGC(INITIAL_GC_DELAY_MS);\n    }\n  }\n\n  stop(): void {\n    if (this.gcTask) {\n      this.gcTask.cancel();\n      this.gcTask = null;\n    }\n  }\n\n  get started(): boolean {\n    return this.gcTask !== null;\n  }\n\n  private scheduleGC(delay: number): void {\n    debugAssert(\n      this.gcTask === null,\n      'Cannot schedule GC while a task is pending'\n    );\n    logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n    this.gcTask = this.asyncQueue.enqueueAfterDelay(\n      TimerId.LruGarbageCollection,\n      delay,\n      async () => {\n        this.gcTask = null;\n        try {\n          await this.localStore.collectGarbage(this.garbageCollector);\n        } catch (e) {\n          if (isIndexedDbTransactionError(e as Error)) {\n            logDebug(\n              LOG_TAG,\n              'Ignoring IndexedDB error during garbage collection: ',\n              e\n            );\n          } else {\n            await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n          }\n        }\n        await this.scheduleGC(REGULAR_GC_DELAY_MS);\n      }\n    );\n  }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n  constructor(\n    private readonly delegate: LruDelegate,\n    readonly params: LruParams\n  ) {}\n\n  calculateTargetCount(\n    txn: PersistenceTransaction,\n    percentile: number\n  ): PersistencePromise<number> {\n    return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n      return Math.floor((percentile / 100.0) * targetCount);\n    });\n  }\n\n  nthSequenceNumber(\n    txn: PersistenceTransaction,\n    n: number\n  ): PersistencePromise<ListenSequenceNumber> {\n    if (n === 0) {\n      return PersistencePromise.resolve(ListenSequence.INVALID);\n    }\n\n    const buffer = new RollingSequenceNumberBuffer(n);\n    return this.delegate\n      .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n      .next(() => {\n        return this.delegate.forEachOrphanedDocumentSequenceNumber(\n          txn,\n          sequenceNumber => buffer.addElement(sequenceNumber)\n        );\n      })\n      .next(() => buffer.maxValue);\n  }\n\n  removeTargets(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<number> {\n    return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n  }\n\n  removeOrphanedDocuments(\n    txn: PersistenceTransaction,\n    upperBound: ListenSequenceNumber\n  ): PersistencePromise<number> {\n    return this.delegate.removeOrphanedDocuments(txn, upperBound);\n  }\n\n  collect(\n    txn: PersistenceTransaction,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<LruResults> {\n    if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n      logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n      return PersistencePromise.resolve(GC_DID_NOT_RUN);\n    }\n\n    return this.getCacheSize(txn).next(cacheSize => {\n      if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n        logDebug(\n          'LruGarbageCollector',\n          `Garbage collection skipped; Cache size ${cacheSize} ` +\n            `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n        );\n        return GC_DID_NOT_RUN;\n      } else {\n        return this.runGarbageCollection(txn, activeTargetIds);\n      }\n    });\n  }\n\n  getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n    return this.delegate.getCacheSize(txn);\n  }\n\n  private runGarbageCollection(\n    txn: PersistenceTransaction,\n    activeTargetIds: ActiveTargets\n  ): PersistencePromise<LruResults> {\n    let upperBoundSequenceNumber: number;\n    let sequenceNumbersToCollect: number, targetsRemoved: number;\n    // Timestamps for various pieces of the process\n    let countedTargetsTs: number,\n      foundUpperBoundTs: number,\n      removedTargetsTs: number,\n      removedDocumentsTs: number;\n    const startTs = Date.now();\n    return this.calculateTargetCount(txn, this.params.percentileToCollect)\n      .next(sequenceNumbers => {\n        // Cap at the configured max\n        if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n          logDebug(\n            'LruGarbageCollector',\n            'Capping sequence numbers to collect down ' +\n              `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n              `from ${sequenceNumbers}`\n          );\n          sequenceNumbersToCollect =\n            this.params.maximumSequenceNumbersToCollect;\n        } else {\n          sequenceNumbersToCollect = sequenceNumbers;\n        }\n        countedTargetsTs = Date.now();\n\n        return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n      })\n      .next(upperBound => {\n        upperBoundSequenceNumber = upperBound;\n        foundUpperBoundTs = Date.now();\n\n        return this.removeTargets(\n          txn,\n          upperBoundSequenceNumber,\n          activeTargetIds\n        );\n      })\n      .next(numTargetsRemoved => {\n        targetsRemoved = numTargetsRemoved;\n        removedTargetsTs = Date.now();\n\n        return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n      })\n      .next(documentsRemoved => {\n        removedDocumentsTs = Date.now();\n\n        if (getLogLevel() <= LogLevel.DEBUG) {\n          const desc =\n            'LRU Garbage Collection\\n' +\n            `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n            `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n            `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n            `\\tRemoved ${targetsRemoved} targets in ` +\n            `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n            `\\tRemoved ${documentsRemoved} documents in ` +\n            `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n            `Total Duration: ${removedDocumentsTs - startTs}ms`;\n          logDebug('LruGarbageCollector', desc);\n        }\n\n        return PersistencePromise.resolve<LruResults>({\n          didRun: true,\n          sequenceNumbersCollected: sequenceNumbersToCollect,\n          targetsRemoved,\n          documentsRemoved\n        });\n      });\n  }\n}\n\nexport function newLruGarbageCollector(\n  delegate: LruDelegate,\n  params: LruParams\n): LruGarbageCollector {\n  return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n  _getProvider,\n  _removeServiceInstance,\n  FirebaseApp,\n  getApp\n} from '@firebase/app';\nimport {\n  createMockUserToken,\n  deepEqual,\n  EmulatorMockTokenOptions,\n  getDefaultEmulatorHostnameAndPort,\n  isCloudWorkstation,\n  pingServer\n} from '@firebase/util';\n\nimport {\n  CredentialsProvider,\n  EmulatorAuthCredentialsProvider,\n  makeAuthCredentialsProvider,\n  OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n  DEFAULT_HOST,\n  FirestoreSettingsImpl,\n  PrivateSettings,\n  FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n  interface NameServiceMapping {\n    'firestore/lite': Firestore;\n  }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n  /**\n   * Whether it's a Firestore or Firestore Lite instance.\n   */\n  type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n  readonly _persistenceKey: string = '(lite)';\n\n  private _settings = new FirestoreSettingsImpl({});\n  private _settingsFrozen = false;\n  private _emulatorOptions: {\n    mockUserToken?: EmulatorMockTokenOptions | string;\n  } = {};\n\n  // A task that is assigned when the terminate() is invoked and resolved when\n  // all components have shut down. Otherwise, Firestore is not terminated,\n  // which can mean either the FirestoreClient is in the process of starting,\n  // or restarting.\n  private _terminateTask: Promise<void> | 'notTerminated' = 'notTerminated';\n\n  /** @hideconstructor */\n  constructor(\n    public _authCredentials: CredentialsProvider<User>,\n    public _appCheckCredentials: CredentialsProvider<string>,\n    readonly _databaseId: DatabaseId,\n    readonly _app?: FirebaseApp\n  ) {}\n\n  /**\n   * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n   * instance.\n   */\n  get app(): FirebaseApp {\n    if (!this._app) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n          'not available'\n      );\n    }\n    return this._app;\n  }\n\n  get _initialized(): boolean {\n    return this._settingsFrozen;\n  }\n\n  get _terminated(): boolean {\n    return this._terminateTask !== 'notTerminated';\n  }\n\n  _setSettings(settings: PrivateSettings): void {\n    if (this._settingsFrozen) {\n      throw new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'Firestore has already been started and its settings can no longer ' +\n          'be changed. You can only modify settings before calling any other ' +\n          'methods on a Firestore object.'\n      );\n    }\n    this._settings = new FirestoreSettingsImpl(settings);\n    this._emulatorOptions = settings.emulatorOptions || {};\n\n    if (settings.credentials !== undefined) {\n      this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n    }\n  }\n\n  _getSettings(): FirestoreSettingsImpl {\n    return this._settings;\n  }\n\n  _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n    return this._emulatorOptions;\n  }\n\n  _freezeSettings(): FirestoreSettingsImpl {\n    this._settingsFrozen = true;\n    return this._settings;\n  }\n\n  _delete(): Promise<void> {\n    // The `_terminateTask` must be assigned future that completes when\n    // terminate is complete. The existence of this future puts SDK in state\n    // that will not accept further API interaction.\n    if (this._terminateTask === 'notTerminated') {\n      this._terminateTask = this._terminate();\n    }\n    return this._terminateTask;\n  }\n\n  async _restart(): Promise<void> {\n    // The `_terminateTask` must equal 'notTerminated' after restart to\n    // signal that client is in a state that accepts API calls.\n    if (this._terminateTask === 'notTerminated') {\n      await this._terminate();\n    } else {\n      this._terminateTask = 'notTerminated';\n    }\n  }\n\n  /** Returns a JSON-serializable representation of this `Firestore` instance. */\n  toJSON(): object {\n    return {\n      app: this._app,\n      databaseId: this._databaseId,\n      settings: this._settings\n    };\n  }\n\n  /**\n   * Terminates all components used by this client. Subclasses can override\n   * this method to clean up their own dependencies, but must also call this\n   * method.\n   *\n   * Only ever called once.\n   */\n  protected _terminate(): Promise<void> {\n    removeComponents(this);\n    return Promise.resolve();\n  }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n  app: FirebaseApp,\n  settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n  app: FirebaseApp,\n  settings: FirestoreSettings,\n  databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n  app: FirebaseApp,\n  settings: FirestoreSettings,\n  databaseId?: string\n): Firestore {\n  if (!databaseId) {\n    databaseId = DEFAULT_DATABASE_NAME;\n  }\n  const provider = _getProvider(app, 'firestore/lite');\n\n  if (provider.isInitialized(databaseId)) {\n    throw new FirestoreError(\n      Code.FAILED_PRECONDITION,\n      'Firestore can only be initialized once per app.'\n    );\n  }\n\n  return provider.initialize({\n    options: settings,\n    instanceIdentifier: databaseId\n  });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n  appOrDatabaseId?: FirebaseApp | string,\n  optionalDatabaseId?: string\n): Firestore {\n  const app: FirebaseApp =\n    typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n  const databaseId =\n    typeof appOrDatabaseId === 'string'\n      ? appOrDatabaseId\n      : optionalDatabaseId || '(default)';\n  const db = _getProvider(app, 'firestore/lite').getImmediate({\n    identifier: databaseId\n  }) as Firestore;\n  if (!db._initialized) {\n    const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n    if (emulator) {\n      connectFirestoreEmulator(db, ...emulator);\n    }\n  }\n  return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n  firestore: Firestore,\n  host: string,\n  port: number,\n  options: {\n    mockUserToken?: EmulatorMockTokenOptions | string;\n  } = {}\n): void {\n  firestore = cast(firestore, Firestore);\n  const useSsl = isCloudWorkstation(host);\n  const settings = firestore._getSettings();\n  const existingConfig = {\n    ...settings,\n    emulatorOptions: firestore._getEmulatorOptions()\n  };\n  const newHostSetting = `${host}:${port}`;\n  if (useSsl) {\n    void pingServer(`https://${newHostSetting}`);\n  }\n  if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n    logWarn(\n      'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n        'will be used.'\n    );\n  }\n  const newConfig = {\n    ...settings,\n    host: newHostSetting,\n    ssl: useSsl,\n    emulatorOptions: options\n  };\n  // No-op if the new configuration matches the current configuration. This supports SSR\n  // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n  if (deepEqual(newConfig, existingConfig)) {\n    return;\n  }\n\n  firestore._setSettings(newConfig);\n\n  if (options.mockUserToken) {\n    let token: string;\n    let user: User;\n    if (typeof options.mockUserToken === 'string') {\n      token = options.mockUserToken;\n      user = User.MOCK_USER;\n    } else {\n      // Let createMockUserToken validate first (catches common mistakes like\n      // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n      token = createMockUserToken(\n        options.mockUserToken,\n        firestore._app?.options.projectId\n      );\n      const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n      if (!uid) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          \"mockUserToken must contain 'sub' or 'user_id' field!\"\n        );\n      }\n      user = new User(uid);\n    }\n\n    firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n      new OAuthToken(token, user)\n    );\n  }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n  firestore = cast(firestore, Firestore);\n  _removeServiceInstance(firestore.app, 'firestore/lite');\n  return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n  newQueryForCollectionGroup,\n  newQueryForPath,\n  Query as InternalQuery,\n  queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n  cast,\n  validateCollectionPath,\n  validateDocumentPath,\n  validateNonEmptyArgument\n} from '../util/input_validation';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n  /** A mapping between a field and its value. */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial<T>`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue<T> =\n  | Partial<T>\n  | (T extends Primitive\n      ? T\n      : T extends {}\n      ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue }\n      : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue<T> =\n  | T\n  | (T extends Primitive\n      ? T\n      : T extends {}\n      ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue }\n      : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData<T> = T extends Primitive\n  ? T\n  : T extends {}\n  ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>\n  : Partial<T>;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n  | {\n      readonly merge?: boolean;\n    }\n  | {\n      readonly mergeFields?: Array<string | FieldPath>;\n    };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /** The type of this Firestore reference. */\n  readonly type: 'query' | 'collection' = 'query';\n\n  /**\n   * The `Firestore` instance for the Firestore database (useful for performing\n   * transactions, etc.).\n   */\n  readonly firestore: Firestore;\n\n  // This is the lite version of the Query class in the main SDK.\n\n  /** @hideconstructor protected */\n  constructor(\n    firestore: Firestore,\n    /**\n     * If provided, the `FirestoreDataConverter` associated with this instance.\n     */\n    readonly converter: FirestoreDataConverter<\n      AppModelType,\n      DbModelType\n    > | null,\n    readonly _query: InternalQuery\n  ) {\n    this.firestore = firestore;\n  }\n\n  /**\n   * Removes the current converter.\n   *\n   * @param converter - `null` removes the current converter.\n   * @returns A `Query<DocumentData, DocumentData>` that does not use a\n   * converter.\n   */\n  withConverter(converter: null): Query<DocumentData, DocumentData>;\n  /**\n   * Applies a custom data converter to this query, allowing you to use your own\n   * custom model objects with Firestore. When you call {@link getDocs} with\n   * the returned query, the provided converter will convert between Firestore\n   * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n   *\n   * @param converter - Converts objects to and from Firestore.\n   * @returns A `Query` that uses the provided converter.\n   */\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): Query<NewAppModelType, NewDbModelType>;\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n  ): Query<NewAppModelType, NewDbModelType> {\n    return new Query<NewAppModelType, NewDbModelType>(\n      this.firestore,\n      converter,\n      this._query\n    );\n  }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> {\n  /** The type of this Firestore reference. */\n  readonly type = 'document';\n\n  /**\n   * The {@link Firestore} instance the document is in.\n   * This is useful for performing transactions, for example.\n   */\n  readonly firestore: Firestore;\n\n  /** @hideconstructor */\n  constructor(\n    firestore: Firestore,\n    /**\n     * If provided, the `FirestoreDataConverter` associated with this instance.\n     */\n    readonly converter: FirestoreDataConverter<\n      AppModelType,\n      DbModelType\n    > | null,\n    readonly _key: DocumentKey\n  ) {\n    this.firestore = firestore;\n  }\n\n  get _path(): ResourcePath {\n    return this._key.path;\n  }\n\n  /**\n   * The document's identifier within its collection.\n   */\n  get id(): string {\n    return this._key.path.lastSegment();\n  }\n\n  /**\n   * A string representing the path of the referenced document (relative\n   * to the root of the database).\n   */\n  get path(): string {\n    return this._key.path.canonicalString();\n  }\n\n  /**\n   * The collection this `DocumentReference` belongs to.\n   */\n  get parent(): CollectionReference<AppModelType, DbModelType> {\n    return new CollectionReference<AppModelType, DbModelType>(\n      this.firestore,\n      this.converter,\n      this._key.path.popLast()\n    );\n  }\n\n  /**\n   * Applies a custom data converter to this `DocumentReference`, allowing you\n   * to use your own custom model objects with Firestore. When you call {@link\n   * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n   * instance, the provided converter will convert between Firestore data of\n   * type `NewDbModelType` and your custom type `NewAppModelType`.\n   *\n   * @param converter - Converts objects to and from Firestore.\n   * @returns A `DocumentReference` that uses the provided converter.\n   */\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): DocumentReference<NewAppModelType, NewDbModelType>;\n  /**\n   * Removes the current converter.\n   *\n   * @param converter - `null` removes the current converter.\n   * @returns A `DocumentReference<DocumentData, DocumentData>` that does not\n   * use a converter.\n   */\n  withConverter(converter: null): DocumentReference<DocumentData, DocumentData>;\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n  ): DocumentReference<NewAppModelType, NewDbModelType> {\n    return new DocumentReference<NewAppModelType, NewDbModelType>(\n      this.firestore,\n      converter,\n      this._key\n    );\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n  static _jsonSchema = {\n    type: property('string', DocumentReference._jsonSchemaVersion),\n    referencePath: property('string')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `DocumentReference` instance.\n   *\n   * @returns a JSON representation of this object.\n   */\n  toJSON(): object {\n    return {\n      type: DocumentReference._jsonSchemaVersion,\n      referencePath: this._key.toString()\n    };\n  }\n\n  /**\n   * Builds a `DocumentReference` instance from a JSON object created by\n   * {@link DocumentReference.toJSON}.\n   *\n   * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n   * @param json - a JSON object represention of a `DocumentReference` instance\n   * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n   * {@link FirestoreError} if an error occurs.\n   */\n  static fromJSON(firestore: Firestore, json: object): DocumentReference;\n  /**\n   * Builds a `DocumentReference` instance from a JSON object created by\n   * {@link DocumentReference.toJSON}.\n   *\n   * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n   * @param json - a JSON object represention of a `DocumentReference` instance\n   * @param converter - Converts objects to and from Firestore.\n   * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n   * {@link FirestoreError} if an error occurs.\n   */\n  static fromJSON<\n    NewAppModelType = DocumentData,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    firestore: Firestore,\n    json: object,\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): DocumentReference<NewAppModelType, NewDbModelType>;\n  static fromJSON<\n    NewAppModelType = DocumentData,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    firestore: Firestore,\n    json: object,\n    converter?: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): DocumentReference<NewAppModelType, NewDbModelType> {\n    if (validateJSON(json, DocumentReference._jsonSchema)) {\n      return new DocumentReference<NewAppModelType, NewDbModelType>(\n        firestore,\n        converter ? converter : null,\n        new DocumentKey(ResourcePath.fromString(json.referencePath))\n      );\n    }\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Unexpected error creating Bytes from JSON.'\n    );\n  }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n  AppModelType = DocumentData,\n  DbModelType extends DocumentData = DocumentData\n> extends Query<AppModelType, DbModelType> {\n  /** The type of this Firestore reference. */\n  readonly type = 'collection';\n\n  /** @hideconstructor */\n  constructor(\n    firestore: Firestore,\n    converter: FirestoreDataConverter<AppModelType, DbModelType> | null,\n    readonly _path: ResourcePath\n  ) {\n    super(firestore, converter, newQueryForPath(_path));\n  }\n\n  /** The collection's identifier. */\n  get id(): string {\n    return this._query.path.lastSegment();\n  }\n\n  /**\n   * A string representing the path of the referenced collection (relative\n   * to the root of the database).\n   */\n  get path(): string {\n    return this._query.path.canonicalString();\n  }\n\n  /**\n   * A reference to the containing `DocumentReference` if this is a\n   * subcollection. If this isn't a subcollection, the reference is null.\n   */\n  get parent(): DocumentReference<DocumentData, DocumentData> | null {\n    const parentPath = this._path.popLast();\n    if (parentPath.isEmpty()) {\n      return null;\n    } else {\n      return new DocumentReference(\n        this.firestore,\n        /* converter= */ null,\n        new DocumentKey(parentPath)\n      );\n    }\n  }\n\n  /**\n   * Applies a custom data converter to this `CollectionReference`, allowing you\n   * to use your own custom model objects with Firestore. When you call {@link\n   * addDoc} with the returned `CollectionReference` instance, the provided\n   * converter will convert between Firestore data of type `NewDbModelType` and\n   * your custom type `NewAppModelType`.\n   *\n   * @param converter - Converts objects to and from Firestore.\n   * @returns A `CollectionReference` that uses the provided converter.\n   */\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n  ): CollectionReference<NewAppModelType, NewDbModelType>;\n  /**\n   * Removes the current converter.\n   *\n   * @param converter - `null` removes the current converter.\n   * @returns A `CollectionReference<DocumentData, DocumentData>` that does not\n   * use a converter.\n   */\n  withConverter(\n    converter: null\n  ): CollectionReference<DocumentData, DocumentData>;\n  withConverter<\n    NewAppModelType,\n    NewDbModelType extends DocumentData = DocumentData\n  >(\n    converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n  ): CollectionReference<NewAppModelType, NewDbModelType> {\n    return new CollectionReference<NewAppModelType, NewDbModelType>(\n      this.firestore,\n      converter,\n      this._path\n    );\n  }\n}\n\nexport function isCollectionReference(\n  val: unknown\n): val is CollectionReference {\n  return val instanceof CollectionReference;\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n  firestore: Firestore,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n  parent:\n    | Firestore\n    | DocumentReference<AppModelType, DbModelType>\n    | CollectionReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData> {\n  parent = getModularInstance(parent);\n\n  validateNonEmptyArgument('collection', 'path', path);\n  if (parent instanceof Firestore) {\n    const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n    validateCollectionPath(absolutePath);\n    return new CollectionReference(parent, /* converter= */ null, absolutePath);\n  } else {\n    if (\n      !(parent instanceof DocumentReference) &&\n      !(parent instanceof CollectionReference)\n    ) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Expected first argument to collection() to be a CollectionReference, ' +\n          'a DocumentReference or FirebaseFirestore'\n      );\n    }\n    const absolutePath = parent._path.child(\n      ResourcePath.fromString(path, ...pathSegments)\n    );\n    validateCollectionPath(absolutePath);\n    return new CollectionReference(\n      parent.firestore,\n      /* converter= */ null,\n      absolutePath\n    );\n  }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n  firestore: Firestore,\n  collectionId: string\n): Query<DocumentData, DocumentData> {\n  firestore = cast(firestore, Firestore);\n\n  validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n  if (collectionId.indexOf('/') >= 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Invalid collection ID '${collectionId}' passed to function ` +\n        `collectionGroup(). Collection IDs must not contain '/'.`\n    );\n  }\n\n  return new Query(\n    firestore,\n    /* converter= */ null,\n    newQueryForCollectionGroup(collectionId)\n  );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n  firestore: Firestore,\n  path: string,\n  ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  path?: string,\n  ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  path: string,\n  ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n  parent:\n    | Firestore\n    | CollectionReference<AppModelType, DbModelType>\n    | DocumentReference<AppModelType, DbModelType>,\n  path?: string,\n  ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType> {\n  parent = getModularInstance(parent);\n\n  // We allow omission of 'pathString' but explicitly prohibit passing in both\n  // 'undefined' and 'null'.\n  if (arguments.length === 1) {\n    path = AutoId.newId();\n  }\n  validateNonEmptyArgument('doc', 'path', path);\n\n  if (parent instanceof Firestore) {\n    const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n    validateDocumentPath(absolutePath);\n    return new DocumentReference(\n      parent,\n      /* converter= */ null,\n      new DocumentKey(absolutePath)\n    );\n  } else {\n    if (\n      !(parent instanceof DocumentReference) &&\n      !(parent instanceof CollectionReference)\n    ) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Expected first argument to doc() to be a CollectionReference, ' +\n          'a DocumentReference or FirebaseFirestore'\n      );\n    }\n    const absolutePath = parent._path.child(\n      ResourcePath.fromString(path, ...pathSegments)\n    );\n    validateDocumentPath(absolutePath);\n    return new DocumentReference<AppModelType, DbModelType>(\n      parent.firestore,\n      parent instanceof CollectionReference ? parent.converter : null,\n      new DocumentKey(absolutePath)\n    );\n  }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual<AppModelType, DbModelType extends DocumentData>(\n  left:\n    | DocumentReference<AppModelType, DbModelType>\n    | CollectionReference<AppModelType, DbModelType>,\n  right:\n    | DocumentReference<AppModelType, DbModelType>\n    | CollectionReference<AppModelType, DbModelType>\n): boolean {\n  left = getModularInstance(left);\n  right = getModularInstance(right);\n\n  if (\n    (left instanceof DocumentReference ||\n      left instanceof CollectionReference) &&\n    (right instanceof DocumentReference || right instanceof CollectionReference)\n  ) {\n    return (\n      left.firestore === right.firestore &&\n      left.path === right.path &&\n      left.converter === right.converter\n    );\n  }\n  return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual<AppModelType, DbModelType extends DocumentData>(\n  left: Query<AppModelType, DbModelType>,\n  right: Query<AppModelType, DbModelType>\n): boolean {\n  left = getModularInstance(left);\n  right = getModularInstance(right);\n\n  if (left instanceof Query && right instanceof Query) {\n    return (\n      left.firestore === right.firestore &&\n      queryEquals(left._query, right._query) &&\n      left.converter === right.converter\n    );\n  }\n  return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n  _byteString: ByteString;\n\n  /** @hideconstructor */\n  constructor(byteString: ByteString) {\n    this._byteString = byteString;\n  }\n\n  /**\n   * Creates a new `Bytes` object from the given Base64 string, converting it to\n   * bytes.\n   *\n   * @param base64 - The Base64 string used to create the `Bytes` object.\n   */\n  static fromBase64String(base64: string): Bytes {\n    try {\n      return new Bytes(ByteString.fromBase64String(base64));\n    } catch (e) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Failed to construct data from Base64 string: ' + e\n      );\n    }\n  }\n\n  /**\n   * Creates a new `Bytes` object from the given Uint8Array.\n   *\n   * @param array - The Uint8Array used to create the `Bytes` object.\n   */\n  static fromUint8Array(array: Uint8Array): Bytes {\n    return new Bytes(ByteString.fromUint8Array(array));\n  }\n\n  /**\n   * Returns the underlying bytes as a Base64-encoded string.\n   *\n   * @returns The Base64-encoded string created from the `Bytes` object.\n   */\n  toBase64(): string {\n    return this._byteString.toBase64();\n  }\n\n  /**\n   * Returns the underlying bytes in a new `Uint8Array`.\n   *\n   * @returns The Uint8Array created from the `Bytes` object.\n   */\n  toUint8Array(): Uint8Array {\n    return this._byteString.toUint8Array();\n  }\n\n  /**\n   * Returns a string representation of the `Bytes` object.\n   *\n   * @returns A string representation of the `Bytes` object.\n   */\n  toString(): string {\n    return 'Bytes(base64: ' + this.toBase64() + ')';\n  }\n\n  /**\n   * Returns true if this `Bytes` object is equal to the provided one.\n   *\n   * @param other - The `Bytes` object to compare against.\n   * @returns true if this `Bytes` object is equal to the provided one.\n   */\n  isEqual(other: Bytes): boolean {\n    return this._byteString.isEqual(other._byteString);\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n  static _jsonSchema = {\n    type: property('string', Bytes._jsonSchemaVersion),\n    bytes: property('string')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `Bytes` instance.\n   *\n   * @returns a JSON representation of this object.\n   */\n  toJSON(): object {\n    return {\n      type: Bytes._jsonSchemaVersion,\n      bytes: this.toBase64()\n    };\n  }\n\n  /**\n   * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n   *\n   * @param json - a JSON object represention of a `Bytes` instance\n   * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n   * {@link FirestoreError} if an error occurs.\n   */\n  static fromJSON(json: object): Bytes {\n    if (validateJSON(json, Bytes._jsonSchema)) {\n      return Bytes.fromBase64String(json.bytes);\n    }\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Unexpected error creating Bytes from JSON.'\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  DOCUMENT_KEY_NAME,\n  FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n  /** Internal representation of a Firestore field path. */\n  readonly _internalPath: InternalFieldPath;\n\n  /**\n   * Creates a `FieldPath` from the provided field names. If more than one field\n   * name is provided, the path will point to a nested field in a document.\n   *\n   * @param fieldNames - A list of field names.\n   */\n  constructor(...fieldNames: string[]) {\n    for (let i = 0; i < fieldNames.length; ++i) {\n      if (fieldNames[i].length === 0) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Invalid field name at argument $(i + 1). ` +\n            'Field names must not be empty.'\n        );\n      }\n    }\n\n    this._internalPath = new InternalFieldPath(fieldNames);\n  }\n\n  /**\n   * Returns true if this `FieldPath` is equal to the provided one.\n   *\n   * @param other - The `FieldPath` to compare against.\n   * @returns true if this `FieldPath` is equal to the provided one.\n   */\n  isEqual(other: FieldPath): boolean {\n    return this._internalPath.isEqual(other._internalPath);\n  }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n  return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n  /**\n   * @param _methodName - The public API endpoint that returns this class.\n   * @hideconstructor\n   */\n  constructor(public _methodName: string) {}\n\n  /** Compares `FieldValue`s for equality. */\n  abstract isEqual(other: FieldValue): boolean;\n  abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n  // Prefix with underscore to signal this is a private variable in JS and\n  // prevent it showing up for autocompletion when typing latitude or longitude.\n  private _lat: number;\n  private _long: number;\n\n  /**\n   * Creates a new immutable `GeoPoint` object with the provided latitude and\n   * longitude values.\n   * @param latitude - The latitude as number between -90 and 90.\n   * @param longitude - The longitude as number between -180 and 180.\n   */\n  constructor(latitude: number, longitude: number) {\n    if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Latitude must be a number between -90 and 90, but was: ' + latitude\n      );\n    }\n    if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        'Longitude must be a number between -180 and 180, but was: ' + longitude\n      );\n    }\n\n    this._lat = latitude;\n    this._long = longitude;\n  }\n\n  /**\n   * The latitude of this `GeoPoint` instance.\n   */\n  get latitude(): number {\n    return this._lat;\n  }\n\n  /**\n   * The longitude of this `GeoPoint` instance.\n   */\n  get longitude(): number {\n    return this._long;\n  }\n\n  /**\n   * Returns true if this `GeoPoint` is equal to the provided one.\n   *\n   * @param other - The `GeoPoint` to compare against.\n   * @returns true if this `GeoPoint` is equal to the provided one.\n   */\n  isEqual(other: GeoPoint): boolean {\n    return this._lat === other._lat && this._long === other._long;\n  }\n\n  /**\n   * Actually private to JS consumers of our API, so this function is prefixed\n   * with an underscore.\n   */\n  _compareTo(other: GeoPoint): number {\n    return (\n      primitiveComparator(this._lat, other._lat) ||\n      primitiveComparator(this._long, other._long)\n    );\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n  static _jsonSchema = {\n    type: property('string', GeoPoint._jsonSchemaVersion),\n    latitude: property('number'),\n    longitude: property('number')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `GeoPoint` instance.\n   *\n   * @returns a JSON representation of this object.\n   */\n  toJSON(): { latitude: number; longitude: number; type: string } {\n    return {\n      latitude: this._lat,\n      longitude: this._long,\n      type: GeoPoint._jsonSchemaVersion\n    };\n  }\n\n  /**\n   * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n   *\n   * @param json - a JSON object represention of a `GeoPoint` instance\n   * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n   * {@link FirestoreError} if an error occurs.\n   */\n  static fromJSON(json: object): GeoPoint {\n    if (validateJSON(json, GeoPoint._jsonSchema)) {\n      return new GeoPoint(json.latitude, json.longitude);\n    }\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Unexpected error creating GeoPoint from JSON.'\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with <code>{@link vector}</code>.\n */\nexport class VectorValue {\n  private readonly _values: number[];\n\n  /**\n   * @private\n   * @internal\n   */\n  constructor(values: number[] | undefined) {\n    // Making a copy of the parameter.\n    this._values = (values || []).map(n => n);\n  }\n\n  /**\n   * Returns a copy of the raw number array form of the vector.\n   */\n  toArray(): number[] {\n    return this._values.map(n => n);\n  }\n\n  /**\n   * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.\n   */\n  isEqual(other: VectorValue): boolean {\n    return isPrimitiveArrayEqual(this._values, other._values);\n  }\n\n  static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n  static _jsonSchema = {\n    type: property('string', VectorValue._jsonSchemaVersion),\n    vectorValues: property('object')\n  };\n\n  /**\n   * Returns a JSON-serializable representation of this `VectorValue` instance.\n   *\n   * @returns a JSON representation of this object.\n   */\n  toJSON(): object {\n    return {\n      type: VectorValue._jsonSchemaVersion,\n      vectorValues: this._values\n    };\n  }\n\n  /**\n   * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n   *\n   * @param json - a JSON object represention of a `VectorValue` instance.\n   * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n   * {@link FirestoreError} if an error occurs.\n   */\n  static fromJSON(json: object): VectorValue {\n    if (validateJSON(json, VectorValue._jsonSchema)) {\n      if (\n        Array.isArray(json.vectorValues) &&\n        json.vectorValues.every(element => typeof element === 'number')\n      ) {\n        return new VectorValue(json.vectorValues);\n      }\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        \"Expected 'vectorValues' field to be a number array\"\n      );\n    }\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      'Unexpected error creating Timestamp from JSON.'\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes<T>(array: T[], value: T): boolean {\n  for (let i = 0; i < array.length; i++) {\n    if (array[i] === value) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some<T>(array: T[], predicate: (t: T) => boolean): boolean {\n  for (let i = 0; i < array.length; i++) {\n    if (predicate(array[i])) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned.  If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex<A>(\n  array: A[],\n  predicate: (value: A) => boolean\n): number | null {\n  for (let i = 0; i < array.length; i++) {\n    if (predicate(array[i])) {\n      return i;\n    }\n  }\n  return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays<T>(\n  before: T[],\n  after: T[],\n  comparator: (l: T, r: T) => number,\n  onAdd: (entry: T) => void,\n  onRemove: (entry: T) => void\n): void {\n  before = [...before];\n  after = [...after];\n  before.sort(comparator);\n  after.sort(comparator);\n\n  const bLen = before.length;\n  const aLen = after.length;\n  let a = 0;\n  let b = 0;\n  while (a < aLen && b < bLen) {\n    const cmp = comparator(before[b], after[a]);\n    if (cmp < 0) {\n      // The element was removed if the next element in our ordered\n      // walkthrough is only in `before`.\n      onRemove(before[b++]);\n    } else if (cmp > 0) {\n      // The element was added if the next element in our ordered walkthrough\n      // is only in `after`.\n      onAdd(after[a++]);\n    } else {\n      a++;\n      b++;\n    }\n  }\n  while (a < aLen) {\n    onAdd(after[a++]);\n  }\n  while (b < bLen) {\n    onRemove(before[b++]);\n  }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left - Array of objects supporting `isEqual`.\n * @param right - Array of objects supporting `isEqual`.\n * @returns True if arrays are equal.\n */\nexport function isArrayEqual<T extends { isEqual: (t: T) => boolean }>(\n  left: T[],\n  right: T[]\n): boolean {\n  if (left.length !== right.length) {\n    return false;\n  }\n\n  for (let i = 0; i < left.length; ++i) {\n    if (!left[i].isEqual(right[i])) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left - Array of primitives.\n * @param right - Array of primitives.\n * @returns True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual<T extends number | string>(\n  left: T[],\n  right: T[]\n): boolean {\n  if (left.length !== right.length) {\n    return false;\n  }\n\n  for (let i = 0; i < left.length; ++i) {\n    if (left[i] !== right[i]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  DocumentData,\n  FieldPath as PublicFieldPath,\n  SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ContextSettings, ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n  FieldTransform,\n  Mutation,\n  PatchMutation,\n  Precondition,\n  SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n  ArrayRemoveTransformOperation,\n  ArrayUnionTransformOperation,\n  NumericIncrementTransformOperation,\n  ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n  TYPE_KEY,\n  VECTOR_MAP_VECTORS_KEY,\n  VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n  MapValue as ProtoMapValue,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n  JsonProtoSerializer,\n  toBytes,\n  toResourceName,\n  toTimestamp,\n  isProtoValueSerializable\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n  DocumentReference,\n  PartialWithFieldValue,\n  WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n  AppModelType,\n  DbModelType extends DocumentData = DocumentData\n> {\n  toFirestore(\n    modelObject: WithFieldValue<AppModelType>\n  ): WithFieldValue<DbModelType>;\n  toFirestore(\n    modelObject: PartialWithFieldValue<AppModelType>,\n    options: SetOptions\n  ): PartialWithFieldValue<DbModelType>;\n  fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n  constructor(\n    readonly data: ObjectValue,\n    readonly fieldMask: FieldMask | null,\n    readonly fieldTransforms: FieldTransform[]\n  ) {}\n\n  toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n    if (this.fieldMask !== null) {\n      return new PatchMutation(\n        key,\n        this.data,\n        this.fieldMask,\n        precondition,\n        this.fieldTransforms\n      );\n    } else {\n      return new SetMutation(\n        key,\n        this.data,\n        precondition,\n        this.fieldTransforms\n      );\n    }\n  }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n  constructor(\n    readonly data: ObjectValue,\n    // The fieldMask does not include document transforms.\n    readonly fieldMask: FieldMask,\n    readonly fieldTransforms: FieldTransform[]\n  ) {}\n\n  toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n    return new PatchMutation(\n      key,\n      this.data,\n      this.fieldMask,\n      precondition,\n      this.fieldTransforms\n    );\n  }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n  Set,\n  Update,\n  MergeSet,\n  /**\n   * Indicates the source is a where clause, cursor bound, arrayUnion()\n   * element, etc. Of note, isWrite(source) will return false.\n   */\n  Argument,\n  /**\n   * Indicates that the source is an Argument that may directly contain nested\n   * arrays (e.g. the operand of an `in` query).\n   */\n  ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n  switch (dataSource) {\n    case UserDataSource.Set: // fall through\n    case UserDataSource.MergeSet: // fall through\n    case UserDataSource.Update:\n      return true;\n    case UserDataSource.Argument:\n    case UserDataSource.ArrayArgument:\n      return false;\n    default:\n      throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n        dataSource\n      });\n  }\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n  readonly fieldTransforms: FieldTransform[];\n  readonly fieldMask: InternalFieldPath[];\n  /**\n   * Initializes a ParseContext with the given source and path.\n   *\n   * @param settings - The settings for the parser.\n   * @param databaseId - The database ID of the Firestore instance.\n   * @param serializer - The serializer to use to generate the Value proto.\n   * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n   * rather than throw.\n   * @param fieldTransforms - A mutable list of field transforms encountered\n   * while parsing the data.\n   * @param fieldMask - A mutable list of field paths encountered while parsing\n   * the data.\n   *\n   * TODO(b/34871131): We don't support array paths right now, so path can be\n   * null to indicate the context represents any location within an array (in\n   * which case certain features will not work and errors will be somewhat\n   * compromised).\n   */\n  constructor(\n    readonly settings: ContextSettings,\n    readonly databaseId: DatabaseId,\n    readonly serializer: JsonProtoSerializer,\n    readonly ignoreUndefinedProperties: boolean,\n    fieldTransforms?: FieldTransform[],\n    fieldMask?: InternalFieldPath[]\n  ) {\n    // Minor hack: If fieldTransforms is undefined, we assume this is an\n    // external call and we need to validate the entire path.\n    if (fieldTransforms === undefined) {\n      this.validatePath();\n    }\n    this.fieldTransforms = fieldTransforms || [];\n    this.fieldMask = fieldMask || [];\n  }\n\n  get path(): InternalFieldPath | undefined {\n    return this.settings.path;\n  }\n\n  get dataSource(): UserDataSource {\n    return this.settings.dataSource;\n  }\n\n  /** Returns a new context with the specified settings overwritten. */\n  contextWith(configuration: Partial<ContextSettings>): ParseContextImpl {\n    return new ParseContextImpl(\n      { ...this.settings, ...configuration },\n      this.databaseId,\n      this.serializer,\n      this.ignoreUndefinedProperties,\n      this.fieldTransforms,\n      this.fieldMask\n    );\n  }\n\n  childContextForField(field: string): ParseContextImpl {\n    const childPath = this.path?.child(field);\n    const context = this.contextWith({ path: childPath, arrayElement: false });\n    context.validatePathSegment(field);\n    return context;\n  }\n\n  childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n    const childPath = this.path?.child(field);\n    const context = this.contextWith({ path: childPath, arrayElement: false });\n    context.validatePath();\n    return context;\n  }\n\n  childContextForArray(index: number): ParseContextImpl {\n    // TODO(b/34871131): We don't support array paths right now; so make path\n    // undefined.\n    return this.contextWith({ path: undefined, arrayElement: true });\n  }\n\n  createError(reason: string): FirestoreError {\n    return createError(\n      reason,\n      this.settings.methodName,\n      this.settings.hasConverter || false,\n      this.path,\n      this.settings.targetDoc\n    );\n  }\n\n  /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n  contains(fieldPath: InternalFieldPath): boolean {\n    return (\n      this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n      this.fieldTransforms.find(transform =>\n        fieldPath.isPrefixOf(transform.field)\n      ) !== undefined\n    );\n  }\n\n  private validatePath(): void {\n    // TODO(b/34871131): Remove null check once we have proper paths for fields\n    // within arrays.\n    if (!this.path) {\n      return;\n    }\n    for (let i = 0; i < this.path.length; i++) {\n      this.validatePathSegment(this.path.get(i));\n    }\n  }\n\n  private validatePathSegment(segment: string): void {\n    if (segment.length === 0) {\n      throw this.createError('Document fields must not be empty');\n    }\n    if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n      throw this.createError('Document fields cannot begin and end with \"__\"');\n    }\n  }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n  private readonly serializer: JsonProtoSerializer;\n\n  constructor(\n    private readonly databaseId: DatabaseId,\n    private readonly ignoreUndefinedProperties: boolean,\n    serializer?: JsonProtoSerializer\n  ) {\n    this.serializer = serializer || newSerializer(databaseId);\n  }\n\n  /** Creates a new top-level parse context. */\n  createContext(\n    dataSource: UserDataSource,\n    methodName: string,\n    targetDoc?: DocumentKey,\n    hasConverter = false\n  ): ParseContextImpl {\n    return new ParseContextImpl(\n      {\n        dataSource,\n        methodName,\n        targetDoc,\n        path: InternalFieldPath.emptyPath(),\n        arrayElement: false,\n        hasConverter\n      },\n      this.databaseId,\n      this.serializer,\n      this.ignoreUndefinedProperties\n    );\n  }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n  const settings = firestore._freezeSettings();\n  const serializer = newSerializer(firestore._databaseId);\n  return new UserDataReader(\n    firestore._databaseId,\n    !!settings.ignoreUndefinedProperties,\n    serializer\n  );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n  userDataReader: UserDataReader,\n  methodName: string,\n  targetDoc: DocumentKey,\n  input: unknown,\n  hasConverter: boolean,\n  options: SetOptions = {}\n): ParsedSetData {\n  const context = userDataReader.createContext(\n    options.merge || options.mergeFields\n      ? UserDataSource.MergeSet\n      : UserDataSource.Set,\n    methodName,\n    targetDoc,\n    hasConverter\n  );\n  validatePlainObject('Data must be an object, but it was:', context, input);\n  const updateData = parseObject(input, context)!;\n\n  let fieldMask: FieldMask | null;\n  let fieldTransforms: FieldTransform[];\n\n  if (options.merge) {\n    fieldMask = new FieldMask(context.fieldMask);\n    fieldTransforms = context.fieldTransforms;\n  } else if (options.mergeFields) {\n    const validatedFieldPaths: InternalFieldPath[] = [];\n\n    for (const stringOrFieldPath of options.mergeFields) {\n      const fieldPath = fieldPathFromArgument(\n        methodName,\n        stringOrFieldPath,\n        targetDoc\n      );\n      if (!context.contains(fieldPath)) {\n        throw new FirestoreError(\n          Code.INVALID_ARGUMENT,\n          `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n        );\n      }\n\n      if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n        validatedFieldPaths.push(fieldPath);\n      }\n    }\n\n    fieldMask = new FieldMask(validatedFieldPaths);\n    fieldTransforms = context.fieldTransforms.filter(transform =>\n      fieldMask!.covers(transform.field)\n    );\n  } else {\n    fieldMask = null;\n    fieldTransforms = context.fieldTransforms;\n  }\n\n  return new ParsedSetData(\n    new ObjectValue(updateData),\n    fieldMask,\n    fieldTransforms\n  );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n  _toFieldTransform(context: ParseContextImpl): null {\n    if (context.dataSource === UserDataSource.MergeSet) {\n      // No transform to add for a delete, but we need to add it to our\n      // fieldMask so it gets deleted.\n      context.fieldMask.push(context.path!);\n    } else if (context.dataSource === UserDataSource.Update) {\n      debugAssert(\n        context.path!.length > 0,\n        `${this._methodName}() at the top level should have already ` +\n          'been handled.'\n      );\n      throw context.createError(\n        `${this._methodName}() can only appear at the top level ` +\n          'of your update data'\n      );\n    } else {\n      // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n      throw context.createError(\n        `${this._methodName}() cannot be used with set() unless you pass ` +\n          '{merge:true}'\n      );\n    }\n    return null;\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return other instanceof DeleteFieldValueImpl;\n  }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n *     context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n  fieldValue: FieldValue,\n  context: ParseContextImpl,\n  arrayElement: boolean\n): ParseContextImpl {\n  return new ParseContextImpl(\n    {\n      dataSource: UserDataSource.Argument,\n      targetDoc: context.settings.targetDoc,\n      methodName: fieldValue._methodName,\n      arrayElement\n    },\n    context.databaseId,\n    context.serializer,\n    context.ignoreUndefinedProperties\n  );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n  _toFieldTransform(context: ParseContextImpl): FieldTransform {\n    return new FieldTransform(context.path!, new ServerTimestampTransform());\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return other instanceof ServerTimestampFieldValueImpl;\n  }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n  constructor(methodName: string, private readonly _elements: unknown[]) {\n    super(methodName);\n  }\n\n  _toFieldTransform(context: ParseContextImpl): FieldTransform {\n    const parseContext = createSentinelChildContext(\n      this,\n      context,\n      /*array=*/ true\n    );\n    const parsedElements = this._elements.map(\n      element => parseData(element, parseContext)!\n    );\n    const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n    return new FieldTransform(context.path!, arrayUnion);\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return (\n      other instanceof ArrayUnionFieldValueImpl &&\n      deepEqual(this._elements, other._elements)\n    );\n  }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n  constructor(methodName: string, private readonly _elements: unknown[]) {\n    super(methodName);\n  }\n\n  _toFieldTransform(context: ParseContextImpl): FieldTransform {\n    const parseContext = createSentinelChildContext(\n      this,\n      context,\n      /*array=*/ true\n    );\n    const parsedElements = this._elements.map(\n      element => parseData(element, parseContext)!\n    );\n    const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n    return new FieldTransform(context.path!, arrayUnion);\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return (\n      other instanceof ArrayRemoveFieldValueImpl &&\n      deepEqual(this._elements, other._elements)\n    );\n  }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n  constructor(methodName: string, private readonly _operand: number) {\n    super(methodName);\n  }\n\n  _toFieldTransform(context: ParseContextImpl): FieldTransform {\n    const numericIncrement = new NumericIncrementTransformOperation(\n      context.serializer,\n      toNumber(context.serializer, this._operand)\n    );\n    return new FieldTransform(context.path!, numericIncrement);\n  }\n\n  isEqual(other: FieldValue): boolean {\n    return (\n      other instanceof NumericIncrementFieldValueImpl &&\n      this._operand === other._operand\n    );\n  }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n  userDataReader: UserDataReader,\n  methodName: string,\n  targetDoc: DocumentKey,\n  input: unknown\n): ParsedUpdateData {\n  const context = userDataReader.createContext(\n    UserDataSource.Update,\n    methodName,\n    targetDoc\n  );\n  validatePlainObject('Data must be an object, but it was:', context, input);\n\n  const fieldMaskPaths: InternalFieldPath[] = [];\n  const updateData = ObjectValue.empty();\n  forEach(input as Dict<unknown>, (key, value) => {\n    const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n    // For Compat types, we have to \"extract\" the underlying types before\n    // performing validation.\n    value = getModularInstance(value);\n\n    const childContext = context.childContextForFieldPath(path);\n    if (value instanceof DeleteFieldValueImpl) {\n      // Add it to the field mask, but don't add anything to updateData.\n      fieldMaskPaths.push(path);\n    } else {\n      const parsedValue = parseData(value, childContext);\n      if (parsedValue != null) {\n        fieldMaskPaths.push(path);\n        updateData.set(path, parsedValue);\n      }\n    }\n  });\n\n  const mask = new FieldMask(fieldMaskPaths);\n  return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n  userDataReader: UserDataReader,\n  methodName: string,\n  targetDoc: DocumentKey,\n  field: string | PublicFieldPath | Compat<PublicFieldPath>,\n  value: unknown,\n  moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n  const context = userDataReader.createContext(\n    UserDataSource.Update,\n    methodName,\n    targetDoc\n  );\n  const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n  const values = [value];\n\n  if (moreFieldsAndValues.length % 2 !== 0) {\n    throw new FirestoreError(\n      Code.INVALID_ARGUMENT,\n      `Function ${methodName}() needs to be called with an even number ` +\n        'of arguments that alternate between field names and values.'\n    );\n  }\n\n  for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n    keys.push(\n      fieldPathFromArgument(\n        methodName,\n        moreFieldsAndValues[i] as string | PublicFieldPath\n      )\n    );\n    values.push(moreFieldsAndValues[i + 1]);\n  }\n\n  const fieldMaskPaths: InternalFieldPath[] = [];\n  const updateData = ObjectValue.empty();\n\n  // We iterate in reverse order to pick the last value for a field if the\n  // user specified the field multiple times.\n  for (let i = keys.length - 1; i >= 0; --i) {\n    if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n      const path = keys[i];\n      let value = values[i];\n\n      // For Compat types, we have to \"extract\" the underlying types before\n      // performing validation.\n      value = getModularInstance(value);\n\n      const childContext = context.childContextForFieldPath(path);\n      if (value instanceof DeleteFieldValueImpl) {\n        // Add it to the field mask, but don't add anything to updateData.\n        fieldMaskPaths.push(path);\n      } else {\n        const parsedValue = parseData(value, childContext);\n        if (parsedValue != null) {\n          fieldMaskPaths.push(path);\n          updateData.set(path, parsedValue);\n        }\n      }\n    }\n  }\n\n  const mask = new FieldMask(fieldMaskPaths);\n  return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n  userDataReader: UserDataReader,\n  methodName: string,\n  input: unknown,\n  allowArrays = false\n): ProtoValue {\n  const context = userDataReader.createContext(\n    allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n    methodName\n  );\n  const parsed = parseData(input, context);\n  debugAssert(parsed != null, 'Parsed data should not be null.');\n  debugAssert(\n    context.fieldTransforms.length === 0,\n    'Field transforms should have been disallowed.'\n  );\n  return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n  input: unknown,\n  context: ParseContext\n): ProtoValue | null {\n  // Unwrap the API type from the Compat SDK. This will return the API type\n  // from firestore-exp.\n  input = getModularInstance(input);\n\n  if (looksLikeJsonObject(input)) {\n    validatePlainObject('Unsupported field value:', context, input);\n    return parseObject(input, context);\n  } else if (input instanceof FieldValue) {\n    // FieldValues usually parse into transforms (except deleteField())\n    // in which case we do not want to include this field in our parsed data\n    // (as doing so will overwrite the field directly prior to the transform\n    // trying to transform it). So we don't add this location to\n    // context.fieldMask and we return null as our parsing result.\n    parseSentinelFieldValue(input, context);\n    return null;\n  } else if (input === undefined && context.ignoreUndefinedProperties) {\n    // If the input is undefined it can never participate in the fieldMask, so\n    // don't handle this below. If `ignoreUndefinedProperties` is false,\n    // `parseScalarValue` will reject an undefined value.\n    return null;\n  } else {\n    // If context.path is null we are inside an array and we don't support\n    // field mask paths more granular than the top-level array.\n    if (context.path) {\n      context.fieldMask.push(context.path);\n    }\n\n    if (input instanceof Array) {\n      // TODO(b/34871131): Include the path containing the array in the error\n      // message.\n      // In the case of IN queries, the parsed data is an array (representing\n      // the set of values to be included for the IN query) that may directly\n      // contain additional arrays (each representing an individual field\n      // value), so we disable this validation.\n      if (\n        context.settings.arrayElement &&\n        context.dataSource !== UserDataSource.ArrayArgument\n      ) {\n        throw context.createError('Nested arrays are not supported');\n      }\n      return parseArray(input as unknown[], context);\n    } else {\n      return parseScalarValue(input, context);\n    }\n  }\n}\n\nexport function parseObject(\n  obj: Dict<unknown>,\n  context: ParseContext\n): { mapValue: ProtoMapValue } {\n  const fields: Dict<ProtoValue> = {};\n\n  if (isEmpty(obj)) {\n    // If we encounter an empty object, we explicitly add it to the update\n    // mask to ensure that the server creates a map entry.\n    if (context.path && context.path.length > 0) {\n      context.fieldMask.push(context.path);\n    }\n  } else {\n    forEach(obj, (key: string, val: unknown) => {\n      const parsedValue = parseData(val, context.childContextForField(key));\n      if (parsedValue != null) {\n        fields[key] = parsedValue;\n      }\n    });\n  }\n\n  return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContext): ProtoValue {\n  const values: ProtoValue[] = [];\n  let entryIndex = 0;\n  for (const entry of array) {\n    let parsedEntry = parseData(\n      entry,\n      context.childContextForArray(entryIndex)\n    );\n    if (parsedEntry == null) {\n      // Just include nulls in the array for fields being replaced with a\n      // sentinel.\n      parsedEntry = { nullValue: 'NULL_VALUE' };\n    }\n    values.push(parsedEntry);\n    entryIndex++;\n  }\n  return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n  value: FieldValue,\n  context: ParseContext\n): void {\n  // Sentinels are only supported with writes, and not within arrays.\n  if (!isWrite(context.dataSource)) {\n    throw context.createError(\n      `${value._methodName}() can only be used with update() and set()`\n    );\n  }\n  if (!context.path) {\n    throw context.createError(\n      `${value._methodName}() is not currently supported inside arrays`\n    );\n  }\n\n  const fieldTransform = value._toFieldTransform(context);\n  if (fieldTransform) {\n    context.fieldTransforms.push(fieldTransform);\n  }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nexport function parseScalarValue(\n  value: unknown,\n  context: ParseContext\n): ProtoValue | null {\n  value = getModularInstance(value);\n\n  if (value === null) {\n    return { nullValue: 'NULL_VALUE' };\n  } else if (typeof value === 'number') {\n    return toNumber(context.serializer, value);\n  } else if (typeof value === 'boolean') {\n    return { booleanValue: value };\n  } else if (typeof value === 'string') {\n    return { stringValue: value };\n  } else if (value instanceof Date) {\n    const timestamp = Timestamp.fromDate(value);\n    return {\n      timestampValue: toTimestamp(context.serializer, timestamp)\n    };\n  } else if (value instanceof Timestamp) {\n    // Firestore backend truncates precision down to microseconds. To ensure\n    // offline mode works the same with regards to truncation, perform the\n    // truncation immediately without waiting for the backend to do that.\n    const timestamp = new Timestamp(\n      value.seconds,\n      Math.floor(value.nanoseconds / 1000) * 1000\n    );\n    return {\n      timestampValue: toTimestamp(context.serializer, timestamp)\n    };\n  } else if (value instanceof GeoPoint) {\n    return {\n      geoPointValue: {\n        latitude: value.latitude,\n        longitude: value.longitude\n      }\n    };\n  } else if (value instanceof Bytes) {\n    return { bytesValue: toBytes(context.serializer, value._byteString) };\n  } else if (value instanceof DocumentReference) {\n    const thisDb = context.databaseId;\n    const otherDb = value.firestore._databaseId;\n    if (!otherDb.isEqual(thisDb)) {\n      throw context.createError(\n        'Document reference is for database ' +\n          `${otherDb.projectId}/${otherDb.database} but should be ` +\n          `for database ${thisDb.projectId}/${thisDb.database}`\n      );\n    }\n    return {\n      referenceValue: toResourceName(\n        value.firestore._databaseId || context.databaseId,\n        value._key.path\n      )\n    };\n  } else if (value instanceof VectorValue) {\n    return parseVectorValue(value, context);\n  } else if (isProtoValueSerializable(value)) {\n    return value._toProto(context.serializer);\n  } else {\n    throw context.createError(\n      `Unsupported field value: ${valueDescription(value)}`\n    );\n  }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n  value: VectorValue | number[],\n  context: ParseContext\n): { mapValue: ProtoMapValue } {\n  const values = value instanceof VectorValue ? value.toArray() : value;\n  const mapValue: ProtoMapValue = {\n    fields: {\n      [TYPE_KEY]: {\n        stringValue: VECTOR_VALUE_SENTINEL\n      },\n      [VECTOR_MAP_VECTORS_KEY]: {\n        arrayValue: {\n          values: values.map(value => {\n            if (typeof value !== 'number') {\n              throw context.createError(\n                'VectorValues must only contain numeric values.'\n              );\n            }\n\n            return toDouble(context.serializer, value);\n          })\n        }\n      }\n    }\n  };\n\n  return { mapValue };\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nexport function looksLikeJsonObject(input: unknown): boolean {\n  return (\n    typeof input === 'object' &&\n    input !== null &&\n    !(input instanceof Array) &&\n    !(input instanceof Date) &&\n    !(input instanceof Timestamp) &&\n    !(input instanceof GeoPoint) &&\n    !(input instanceof Bytes) &&\n    !(input instanceof DocumentReference) &&\n    !(input instanceof FieldValue) &&\n    !(input instanceof VectorValue) &&\n    !isProtoValueSerializable(input)\n  );\n}\n\nfunction validatePlainObject(\n  message: string,\n  context: ParseContext,\n  input: unknown\n): asserts input is Dict<unknown> {\n  if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n    const description = valueDescription(input);\n    if (description === 'an object') {\n      // Massage the error if it was an object.\n      throw context.createError(message + ' a custom object');\n    } else {\n      throw context.createError(message + ' ' + description);\n    }\n  }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n  methodName: string,\n  path: string | PublicFieldPath | Compat<PublicFieldPath>,\n  targetDoc?: DocumentKey\n): InternalFieldPath {\n  // If required, replace the FieldPath Compat class with the firestore-exp\n  // FieldPath.\n  path = getModularInstance(path);\n\n  if (path instanceof FieldPath) {\n    return path._internalPath;\n  } else if (typeof path === 'string') {\n    return fieldPathFromDotSeparatedString(methodName, path);\n  } else {\n    const message = 'Field path arguments must be of type string or ';\n    throw createError(\n      message,\n      methodName,\n      /* hasConverter= */ false,\n      /* path= */ undefined,\n      targetDoc\n    );\n  }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n  methodName: string,\n  path: string,\n  targetDoc?: DocumentKey\n): InternalFieldPath {\n  const found = path.search(FIELD_PATH_RESERVED);\n  if (found >= 0) {\n    throw createError(\n      `Invalid field path (${path}). Paths must not contain ` +\n        `'~', '*', '/', '[', or ']'`,\n      methodName,\n      /* hasConverter= */ false,\n      /* path= */ undefined,\n      targetDoc\n    );\n  }\n\n  try {\n    return new FieldPath(...path.split('.'))._internalPath;\n  } catch (e) {\n    throw createError(\n      `Invalid field path (${path}). Paths must not be empty, ` +\n        `begin with '.', end with '.', or contain '..'`,\n      methodName,\n      /* hasConverter= */ false,\n      /* path= */ undefined,\n      targetDoc\n    );\n  }\n}\n\nfunction createError(\n  reason: string,\n  methodName: string,\n  hasConverter: boolean,\n  path?: InternalFieldPath,\n  targetDoc?: DocumentKey\n): FirestoreError {\n  const hasPath = path && !path.isEmpty();\n  const hasDocument = targetDoc !== undefined;\n  let message = `Function ${methodName}() called with invalid data`;\n  if (hasConverter) {\n    message += ' (via `toFirestore()`)';\n  }\n  message += '. ';\n\n  let description = '';\n  if (hasPath || hasDocument) {\n    description += ' (found';\n\n    if (hasPath) {\n      description += ` in field ${path}`;\n    }\n    if (hasDocument) {\n      description += ` in document ${targetDoc}`;\n    }\n    description += ')';\n  }\n\n  return new FirestoreError(\n    Code.INVALID_ARGUMENT,\n    message + reason + description\n  );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n  haystack: InternalFieldPath[],\n  needle: InternalFieldPath\n): boolean {\n  return haystack.some(v => v.isEqual(needle));\n}\n\nexport interface UserData {\n  _readUserData(context: ParseContext): void;\n}\n\nexport function isUserData(value: unknown): value is UserData {\n  return typeof (value as UserData)._readUserData === 'function';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n  normalizeByteString,\n  normalizeNumber,\n  normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n  getLocalWriteTime,\n  getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n  ApiClientObjectMap,\n  ArrayValue as ProtoArrayValue,\n  LatLng as ProtoLatLng,\n  MapValue as ProtoMapValue,\n  Timestamp as ProtoTimestamp,\n  Value,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n  convertValue(\n    value: ProtoValue,\n    serverTimestampBehavior: ServerTimestampBehavior = 'none'\n  ): unknown {\n    switch (typeOrder(value)) {\n      case TypeOrder.NullValue:\n        return null;\n      case TypeOrder.BooleanValue:\n        return value.booleanValue!;\n      case TypeOrder.NumberValue:\n        return normalizeNumber(value.integerValue || value.doubleValue);\n      case TypeOrder.TimestampValue:\n        return this.convertTimestamp(value.timestampValue!);\n      case TypeOrder.ServerTimestampValue:\n        return this.convertServerTimestamp(value, serverTimestampBehavior);\n      case TypeOrder.StringValue:\n        return value.stringValue!;\n      case TypeOrder.BlobValue:\n        return this.convertBytes(normalizeByteString(value.bytesValue!));\n      case TypeOrder.RefValue:\n        return this.convertReference(value.referenceValue!);\n      case TypeOrder.GeoPointValue:\n        return this.convertGeoPoint(value.geoPointValue!);\n      case TypeOrder.ArrayValue:\n        return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n      case TypeOrder.ObjectValue:\n        return this.convertObject(value.mapValue!, serverTimestampBehavior);\n      case TypeOrder.VectorValue:\n        return this.convertVectorValue(value.mapValue!);\n      default:\n        throw fail(0xf2a2, 'Invalid value type', {\n          value\n        });\n    }\n  }\n\n  private convertObject(\n    mapValue: ProtoMapValue,\n    serverTimestampBehavior: ServerTimestampBehavior\n  ): DocumentData {\n    return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n  }\n\n  /**\n   * @internal\n   */\n  convertObjectMap(\n    fields: ApiClientObjectMap<Value> | undefined,\n    serverTimestampBehavior: ServerTimestampBehavior = 'none'\n  ): DocumentData {\n    const result: DocumentData = {};\n    forEach(fields, (key, value) => {\n      result[key] = this.convertValue(value, serverTimestampBehavior);\n    });\n    return result;\n  }\n\n  /**\n   * @internal\n   */\n  convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n    const values = mapValue.fields?.[\n      VECTOR_MAP_VECTORS_KEY\n    ].arrayValue?.values?.map(value => {\n      return normalizeNumber(value.doubleValue);\n    });\n\n    return new VectorValue(values);\n  }\n\n  private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n    return new GeoPoint(\n      normalizeNumber(value.latitude),\n      normalizeNumber(value.longitude)\n    );\n  }\n\n  private convertArray(\n    arrayValue: ProtoArrayValue,\n    serverTimestampBehavior: ServerTimestampBehavior\n  ): unknown[] {\n    return (arrayValue.values || []).map(value =>\n      this.convertValue(value, serverTimestampBehavior)\n    );\n  }\n\n  private convertServerTimestamp(\n    value: ProtoValue,\n    serverTimestampBehavior: ServerTimestampBehavior\n  ): unknown {\n    switch (serverTimestampBehavior) {\n      case 'previous':\n        const previousValue = getPreviousValue(value);\n        if (previousValue == null) {\n          return null;\n        }\n        return this.convertValue(previousValue, serverTimestampBehavior);\n      case 'estimate':\n        return this.convertTimestamp(getLocalWriteTime(value));\n      default:\n        return null;\n    }\n  }\n\n  private convertTimestamp(value: ProtoTimestamp): Timestamp {\n    const normalizedValue = normalizeTimestamp(value);\n    return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n  }\n\n  protected convertDocumentKey(\n    name: string,\n    expectedDatabaseId: DatabaseId\n  ): DocumentKey {\n    const resourcePath = ResourcePath.fromString(name);\n    hardAssert(\n      isValidResourceName(resourcePath),\n      0x25d8,\n      'ReferenceValue is not valid',\n      { name }\n    );\n    const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n    const key = new DocumentKey(resourcePath.popFirst(5));\n\n    if (!databaseId.isEqual(expectedDatabaseId)) {\n      // TODO(b/64130202): Somehow support foreign references.\n      logError(\n        `Document ${key} contains a document ` +\n          `reference within a different database (` +\n          `${databaseId.projectId}/${databaseId.database}) which is not ` +\n          `supported. It will be treated as a reference in the current ` +\n          `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n          `instead.`\n      );\n    }\n    return key;\n  }\n\n  protected abstract convertReference(name: string): unknown;\n\n  protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  DocumentData as PublicDocumentData,\n  SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n  invokeBatchGetDocumentsRpc,\n  invokeCommitRpc,\n  invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n  CollectionReference,\n  doc,\n  DocumentData,\n  DocumentReference,\n  PartialWithFieldValue,\n  Query,\n  SetOptions,\n  UpdateData,\n  WithFieldValue\n} from './reference';\nimport {\n  DocumentSnapshot,\n  QueryDocumentSnapshot,\n  QuerySnapshot\n} from './snapshot';\nimport {\n  newUserDataReader,\n  ParsedUpdateData,\n  parseSetData,\n  parseUpdateData,\n  parseUpdateVarargs,\n  UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter<T>(\n  converter: UntypedFirestoreDataConverter<T> | null,\n  value: WithFieldValue<T> | PartialWithFieldValue<T>,\n  options?: PublicSetOptions\n): PublicDocumentData {\n  let convertedValue;\n  if (converter) {\n    if (options && (options.merge || options.mergeFields)) {\n      // Cast to `any` in order to satisfy the union type constraint on\n      // toFirestore().\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      convertedValue = (converter as any).toFirestore(value, options);\n    } else {\n      convertedValue = converter.toFirestore(value as WithFieldValue<T>);\n    }\n  } else {\n    convertedValue = value as PublicDocumentData;\n  }\n  return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n  constructor(protected firestore: Firestore) {\n    super();\n  }\n\n  protected convertBytes(bytes: ByteString): Bytes {\n    return new Bytes(bytes);\n  }\n\n  protected convertReference(name: string): DocumentReference {\n    const key = this.convertDocumentKey(name, this.firestore._databaseId);\n    return new DocumentReference(this.firestore, /* converter= */ null, key);\n  }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const datastore = getDatastore(reference.firestore);\n  const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n  return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n    result => {\n      hardAssert(\n        result.length === 1,\n        0x3d02,\n        'Expected a single document result'\n      );\n      const document = result[0];\n      return new DocumentSnapshot<AppModelType, DbModelType>(\n        reference.firestore,\n        userDataWriter,\n        reference._key,\n        document.isFoundDocument() ? document : null,\n        reference.converter\n      );\n    }\n  );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n  query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n  query = cast<Query<AppModelType, DbModelType>>(query, Query);\n  validateHasExplicitOrderByForLimitToLast(query._query);\n\n  const datastore = getDatastore(query.firestore);\n  const userDataWriter = new LiteUserDataWriter(query.firestore);\n  return invokeRunQueryRpc(datastore, query._query).then(result => {\n    const docs = result.map(\n      doc =>\n        new QueryDocumentSnapshot<AppModelType, DbModelType>(\n          query.firestore,\n          userDataWriter,\n          doc.key,\n          doc,\n          query.converter\n        )\n    );\n\n    if (query._query.limitType === LimitType.Last) {\n      // Limit to last queries reverse the orderBy constraint that was\n      // specified by the user. As such, we need to reverse the order of the\n      // results to return the documents in the expected order.\n      docs.reverse();\n    }\n\n    return new QuerySnapshot<AppModelType, DbModelType>(query, docs);\n  });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: PartialWithFieldValue<AppModelType>,\n  options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: PartialWithFieldValue<AppModelType>,\n  options?: SetOptions\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const convertedValue = applyFirestoreDataConverter(\n    reference.converter,\n    data,\n    options\n  );\n  const dataReader = newUserDataReader(reference.firestore);\n  const parsed = parseSetData(\n    dataReader,\n    'setDoc',\n    reference._key,\n    convertedValue,\n    reference.converter !== null,\n    options\n  );\n\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    parsed.toMutation(reference._key, Precondition.none())\n  ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  field: string | FieldPath,\n  value: unknown,\n  ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>,\n  fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n  value?: unknown,\n  ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const dataReader = newUserDataReader(reference.firestore);\n\n  // For Compat types, we have to \"extract\" the underlying types before\n  // performing validation.\n  fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n  let parsed: ParsedUpdateData;\n  if (\n    typeof fieldOrUpdateData === 'string' ||\n    fieldOrUpdateData instanceof FieldPath\n  ) {\n    parsed = parseUpdateVarargs(\n      dataReader,\n      'updateDoc',\n      reference._key,\n      fieldOrUpdateData,\n      value,\n      moreFieldsAndValues\n    );\n  } else {\n    parsed = parseUpdateData(\n      dataReader,\n      'updateDoc',\n      reference._key,\n      fieldOrUpdateData\n    );\n  }\n\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    parsed.toMutation(reference._key, Precondition.exists(true))\n  ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n  reference = cast<DocumentReference<AppModelType, DbModelType>>(\n    reference,\n    DocumentReference\n  );\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    new DeleteMutation(reference._key, Precondition.none())\n  ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n  reference: CollectionReference<AppModelType, DbModelType>,\n  data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n  reference = cast<CollectionReference<AppModelType, DbModelType>>(\n    reference,\n    CollectionReference\n  );\n  const docRef = doc(reference);\n\n  const convertedValue = applyFirestoreDataConverter(\n    reference.converter,\n    data as PartialWithFieldValue<AppModelType>\n  );\n\n  const dataReader = newUserDataReader(reference.firestore);\n  const parsed = parseSetData(\n    dataReader,\n    'addDoc',\n    docRef._key,\n    convertedValue,\n    docRef.converter !== null,\n    {}\n  );\n\n  const datastore = getDatastore(reference.firestore);\n  return invokeCommitRpc(datastore, [\n    parsed.toMutation(docRef._key, Precondition.exists(false))\n  ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n  ArrayRemoveFieldValueImpl,\n  ArrayUnionFieldValueImpl,\n  DeleteFieldValueImpl,\n  NumericIncrementFieldValueImpl,\n  ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n  return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n  return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n  // NOTE: We don't actually parse the data until it's used in set() or\n  // update() since we'd need the Firestore instance to do this.\n  return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n  // NOTE: We don't actually parse the data until it's used in set() or\n  // update() since we'd need the Firestore instance to do this.\n  return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n  return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n  return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { parseData } from '../lite-api/user_data_reader';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { isPlainObject } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\nexport type OptionsDefinitions = Record<string, OptionDefinition>;\nexport interface OptionDefinition {\n  serverName: string;\n  nestedOptions?: OptionsDefinitions;\n}\n\nexport class OptionsUtil {\n  constructor(private optionDefinitions: OptionsDefinitions) {}\n\n  private _getKnownOptions(\n    options: Record<string, unknown>,\n    context: ParseContext\n  ): ObjectValue {\n    const knownOptions: ObjectValue = ObjectValue.empty();\n\n    // SERIALIZE KNOWN OPTIONS\n    for (const knownOptionKey in this.optionDefinitions) {\n      if (this.optionDefinitions.hasOwnProperty(knownOptionKey)) {\n        const optionDefinition: OptionDefinition =\n          this.optionDefinitions[knownOptionKey];\n\n        if (knownOptionKey in options) {\n          const optionValue: unknown = options[knownOptionKey];\n          let protoValue: Value | undefined = undefined;\n\n          if (optionDefinition.nestedOptions && isPlainObject(optionValue)) {\n            const nestedUtil = new OptionsUtil(optionDefinition.nestedOptions);\n            protoValue = {\n              mapValue: {\n                fields: nestedUtil.getOptionsProto(context, optionValue)\n              }\n            };\n          } else if (optionValue) {\n            protoValue = parseData(optionValue, context) ?? undefined;\n          }\n\n          if (protoValue) {\n            knownOptions.set(\n              FieldPath.fromServerFormat(optionDefinition.serverName),\n              protoValue\n            );\n          }\n        }\n      }\n    }\n\n    return knownOptions;\n  }\n\n  getOptionsProto(\n    context: ParseContext,\n    knownOptions: Record<string, unknown>,\n    optionsOverride?: Record<string, unknown>\n  ): ApiClientObjectMap<Value> | undefined {\n    const result: ObjectValue = this._getKnownOptions(knownOptions, context);\n\n    // APPLY OPTIONS OVERRIDES\n    if (optionsOverride) {\n      const optionsMap = new Map(\n        mapToArray(optionsOverride, (value, key) => [\n          FieldPath.fromServerFormat(key),\n          value !== undefined ? parseData(value, context) : null\n        ])\n      );\n      result.setAll(optionsMap);\n    }\n\n    // Return MapValue from `result` or empty map value\n    return result.value.mapValue.fields ?? {};\n  }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { UserData } from '../lite-api/user_data_reader';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Pipeline as PipelineProto,\n  StructuredPipeline as StructuredPipelineProto\n} from '../protos/firestore_proto_api';\nimport { JsonProtoSerializer, ProtoSerializable } from '../remote/serializer';\n\nimport { OptionsUtil } from './options_util';\n\nexport class StructuredPipelineOptions implements UserData {\n  proto: ApiClientObjectMap<firestoreV1ApiClientInterfaces.Value> | undefined;\n\n  readonly optionsUtil = new OptionsUtil({\n    indexMode: {\n      serverName: 'index_mode'\n    }\n  });\n\n  constructor(\n    private _userOptions: Record<string, unknown> = {},\n    private _optionsOverride: Record<string, unknown> = {}\n  ) {}\n\n  _readUserData(context: ParseContext): void {\n    this.proto = this.optionsUtil.getOptionsProto(\n      context,\n      this._userOptions,\n      this._optionsOverride\n    );\n  }\n}\n\nexport class StructuredPipeline\n  implements ProtoSerializable<StructuredPipelineProto>\n{\n  constructor(\n    private pipeline: ProtoSerializable<PipelineProto>,\n    private options: StructuredPipelineOptions\n  ) {}\n\n  _toProto(serializer: JsonProtoSerializer): StructuredPipelineProto {\n    return {\n      pipeline: this.pipeline._toProto(serializer),\n      options: this.options.proto\n    };\n  }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  ArrayValue as ProtoArrayValue,\n  Function as ProtoFunction,\n  LatLng as ProtoLatLng,\n  MapValue as ProtoMapValue,\n  Pipeline as ProtoPipeline,\n  Timestamp as ProtoTimestamp,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\n\nimport { isPlainObject } from './input_validation';\n\n/* eslint @typescript-eslint/no-explicit-any: 0 */\n\nfunction isITimestamp(obj: any): obj is ProtoTimestamp {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if (\n    'seconds' in obj &&\n    (obj.seconds === null ||\n      typeof obj.seconds === 'number' ||\n      typeof obj.seconds === 'string') &&\n    'nanos' in obj &&\n    (obj.nanos === null || typeof obj.nanos === 'number')\n  ) {\n    return true;\n  }\n\n  return false;\n}\nfunction isILatLng(obj: any): obj is ProtoLatLng {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if (\n    'latitude' in obj &&\n    (obj.latitude === null || typeof obj.latitude === 'number') &&\n    'longitude' in obj &&\n    (obj.longitude === null || typeof obj.longitude === 'number')\n  ) {\n    return true;\n  }\n\n  return false;\n}\nfunction isIArrayValue(obj: any): obj is ProtoArrayValue {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if ('values' in obj && (obj.values === null || Array.isArray(obj.values))) {\n    return true;\n  }\n\n  return false;\n}\nfunction isIMapValue(obj: any): obj is ProtoMapValue {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if ('fields' in obj && (obj.fields === null || isPlainObject(obj.fields))) {\n    return true;\n  }\n\n  return false;\n}\nfunction isIFunction(obj: any): obj is ProtoFunction {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if (\n    'name' in obj &&\n    (obj.name === null || typeof obj.name === 'string') &&\n    'args' in obj &&\n    (obj.args === null || Array.isArray(obj.args))\n  ) {\n    return true;\n  }\n\n  return false;\n}\n\nfunction isIPipeline(obj: any): obj is ProtoPipeline {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n  if ('stages' in obj && (obj.stages === null || Array.isArray(obj.stages))) {\n    return true;\n  }\n\n  return false;\n}\n\nexport function isFirestoreValue(obj: any): obj is ProtoValue {\n  if (typeof obj !== 'object' || obj === null) {\n    return false; // Must be a non-null object\n  }\n\n  // Check optional properties and their types\n  if (\n    ('nullValue' in obj &&\n      (obj.nullValue === null || obj.nullValue === 'NULL_VALUE')) ||\n    ('booleanValue' in obj &&\n      (obj.booleanValue === null || typeof obj.booleanValue === 'boolean')) ||\n    ('integerValue' in obj &&\n      (obj.integerValue === null ||\n        typeof obj.integerValue === 'number' ||\n        typeof obj.integerValue === 'string')) ||\n    ('doubleValue' in obj &&\n      (obj.doubleValue === null || typeof obj.doubleValue === 'number')) ||\n    ('timestampValue' in obj &&\n      (obj.timestampValue === null || isITimestamp(obj.timestampValue))) ||\n    ('stringValue' in obj &&\n      (obj.stringValue === null || typeof obj.stringValue === 'string')) ||\n    ('bytesValue' in obj &&\n      (obj.bytesValue === null || obj.bytesValue instanceof Uint8Array)) ||\n    ('referenceValue' in obj &&\n      (obj.referenceValue === null ||\n        typeof obj.referenceValue === 'string')) ||\n    ('geoPointValue' in obj &&\n      (obj.geoPointValue === null || isILatLng(obj.geoPointValue))) ||\n    ('arrayValue' in obj &&\n      (obj.arrayValue === null || isIArrayValue(obj.arrayValue))) ||\n    ('mapValue' in obj &&\n      (obj.mapValue === null || isIMapValue(obj.mapValue))) ||\n    ('fieldReferenceValue' in obj &&\n      (obj.fieldReferenceValue === null ||\n        typeof obj.fieldReferenceValue === 'string')) ||\n    ('functionValue' in obj &&\n      (obj.functionValue === null || isIFunction(obj.functionValue))) ||\n    ('pipelineValue' in obj &&\n      (obj.pipelineValue === null || isIPipeline(obj.pipelineValue)))\n  ) {\n    return true;\n  }\n\n  return false;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ParseContext } from '../api/parse_context';\nimport { OptionsUtil } from '../core/options_util';\nimport {\n  DOCUMENT_KEY_NAME,\n  FieldPath as InternalFieldPath\n} from '../model/path';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport {\n  JsonProtoSerializer,\n  ProtoValueSerializable,\n  toMapValue,\n  toPipelineValue,\n  toStringValue\n} from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { isPlainObject } from '../util/input_validation';\nimport { isFirestoreValue } from '../util/proto';\nimport { isString } from '../util/types';\n\nimport { Bytes } from './bytes';\nimport { documentId as documentIdFieldPath, FieldPath } from './field_path';\nimport { vector } from './field_value_impl';\nimport { GeoPoint } from './geo_point';\nimport type { Pipeline } from './pipeline';\nimport { DocumentReference } from './reference';\nimport { Timestamp } from './timestamp';\nimport { fieldPathFromArgument, parseData, UserData } from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n *\n * An enumeration of the different types of expressions.\n */\nexport type ExpressionType =\n  | 'Field'\n  | 'Constant'\n  | 'Function'\n  | 'AggregateFunction'\n  | 'ListOfExpressions'\n  | 'AliasedExpression'\n  | 'Variable'\n  | 'PipelineValue';\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n *\n * @private\n * @internal\n * @param value\n */\nfunction valueToDefaultExpr(value: unknown): Expression {\n  let result: Expression | undefined;\n  if (value instanceof Expression) {\n    return value;\n  } else if (isPlainObject(value)) {\n    result = _map(value as Record<string, unknown>, undefined);\n  } else if (value instanceof Array) {\n    result = array(value);\n  } else {\n    result = _constant(value, undefined);\n  }\n\n  return result;\n}\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n *\n * @private\n * @internal\n * @param value\n */\nfunction vectorToExpr(value: VectorValue | number[] | Expression): Expression {\n  if (value instanceof Expression) {\n    return value;\n  } else if (value instanceof VectorValue) {\n    return constant(value);\n  } else if (Array.isArray(value)) {\n    return constant(vector(value));\n  } else {\n    throw new Error('Unsupported value: ' + typeof value);\n  }\n}\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n * If the input is a string, it is assumed to be a field name, and a\n * field(value) is returned.\n *\n * @private\n * @internal\n * @param value\n */\nfunction fieldOrExpression(value: unknown): Expression {\n  if (isString(value)) {\n    const result = field(value);\n    return result;\n  } else {\n    return valueToDefaultExpr(value);\n  }\n}\n/**\n *\n * Represents an expression that can be evaluated to a value within the execution of a {@link\n * @firebase/firestore/pipelines#Pipeline}.\n *\n * Expressions are the building blocks for creating complex queries and transformations in\n * Firestore pipelines. They can represent:\n *\n * - **Field references:** Access values from document fields.\n * - **Literals:** Represent constant values (strings, numbers, booleans).\n * - **Function calls:** Apply functions to one or more expressions.\n *\n * The `Expression` class provides a fluent API for building expressions. You can chain together\n * method calls to create complex expressions.\n */\nexport abstract class Expression implements ProtoValueSerializable, UserData {\n  abstract readonly expressionType: ExpressionType;\n\n  abstract readonly _methodName?: string;\n\n  /**\n   * @private\n   * @internal\n   */\n  abstract _toProto(serializer: JsonProtoSerializer): ProtoValue;\n  _protoValueType = 'ProtoValue' as const;\n\n  /**\n   * @private\n   * @internal\n   */\n  abstract _readUserData(context: ParseContext): void;\n\n  /**\n   * Creates an expression that adds this expression to another expression.\n   *\n   * @example\n   * ```typescript\n   * // Add the value of the 'quantity' field and the 'reserve' field.\n   * field(\"quantity\").add(field(\"reserve\"));\n   * ```\n   *\n   * @param second - The expression or literal to add to this expression.\n   * @param others - Optional additional expressions or literals to add to this expression.\n   * @returns A new `Expression` representing the addition operation.\n   */\n  add(second: Expression | unknown): FunctionExpression {\n    return new FunctionExpression(\n      'add',\n      [this, valueToDefaultExpr(second)],\n      'add'\n    );\n  }\n\n  /**\n   * Wraps the expression in a [BooleanExpression].\n   *\n   * @returns A [BooleanExpression] representing the same expression.\n   */\n  asBoolean(): BooleanExpression {\n    if (this instanceof BooleanExpression) {\n      return this;\n    } else if (this instanceof Constant) {\n      return new BooleanConstant(this);\n    } else if (this instanceof Field) {\n      return new BooleanField(this);\n    } else if (this instanceof FunctionExpression) {\n      return new BooleanFunctionExpression(this);\n    } else {\n      throw new FirestoreError(\n        'invalid-argument',\n        `Conversion of type ${typeof this} to BooleanExpression not supported.`\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that subtracts another expression from this expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract the 'discount' field from the 'price' field\n   * field(\"price\").subtract(field(\"discount\"));\n   * ```\n   *\n   * @param subtrahend - The expression to subtract from this expression.\n   * @returns A new `Expression` representing the subtraction operation.\n   */\n  subtract(subtrahend: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that subtracts a constant value from this expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract 20 from the value of the 'total' field\n   * field(\"total\").subtract(20);\n   * ```\n   *\n   * @param subtrahend - The constant value to subtract.\n   * @returns A new `Expression` representing the subtraction operation.\n   */\n  subtract(subtrahend: number): FunctionExpression;\n  subtract(subtrahend: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'subtract',\n      [this, valueToDefaultExpr(subtrahend)],\n      'subtract'\n    );\n  }\n\n  /**\n   * Creates an expression that multiplies this expression by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Multiply the 'quantity' field by the 'price' field\n   * field(\"quantity\").multiply(field(\"price\"));\n   * ```\n   *\n   * @param second - The second expression or literal to multiply by.\n   * @param others - Optional additional expressions or literals to multiply by.\n   * @returns A new `Expression` representing the multiplication operation.\n   */\n  multiply(second: Expression | number): FunctionExpression {\n    return new FunctionExpression(\n      'multiply',\n      [this, valueToDefaultExpr(second)],\n      'multiply'\n    );\n  }\n\n  /**\n   * Creates an expression that divides this expression by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Divide the 'total' field by the 'count' field\n   * field(\"total\").divide(field(\"count\"));\n   * ```\n   *\n   * @param divisor - The expression to divide by.\n   * @returns A new `Expression` representing the division operation.\n   */\n  divide(divisor: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that divides this expression by a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Divide the 'value' field by 10\n   * field(\"value\").divide(10);\n   * ```\n   *\n   * @param divisor - The constant value to divide by.\n   * @returns A new `Expression` representing the division operation.\n   */\n  divide(divisor: number): FunctionExpression;\n  divide(divisor: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'divide',\n      [this, valueToDefaultExpr(divisor)],\n      'divide'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the remainder of dividing the 'value' field by the 'divisor' field\n   * field(\"value\").mod(field(\"divisor\"));\n   * ```\n   *\n   * @param expression - The expression to divide by.\n   * @returns A new `Expression` representing the modulo operation.\n   */\n  mod(expression: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the remainder of dividing the 'value' field by 10\n   * field(\"value\").mod(10);\n   * ```\n   *\n   * @param value - The constant value to divide by.\n   * @returns A new `Expression` representing the modulo operation.\n   */\n  mod(value: number): FunctionExpression;\n  mod(other: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'mod',\n      [this, valueToDefaultExpr(other)],\n      'mod'\n    );\n  }\n\n  /**\n   * Creates an expression that checks if this expression is equal to another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'age' field is equal to 21\n   * field(\"age\").equal(21);\n   * ```\n   *\n   * @param expression - The expression to compare for equality.\n   * @returns A new `Expression` representing the equality comparison.\n   */\n  equal(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is equal to a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'city' field is equal to \"London\"\n   * field(\"city\").equal(\"London\");\n   * ```\n   *\n   * @param value - The constant value to compare for equality.\n   * @returns A new `Expression` representing the equality comparison.\n   */\n  equal(value: unknown): BooleanExpression;\n  equal(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'equal',\n      [this, valueToDefaultExpr(other)],\n      'equal'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is not equal to another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'status' field is not equal to \"completed\"\n   * field(\"status\").notEqual(\"completed\");\n   * ```\n   *\n   * @param expression - The expression to compare for inequality.\n   * @returns A new `Expression` representing the inequality comparison.\n   */\n  notEqual(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is not equal to a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'country' field is not equal to \"USA\"\n   * field(\"country\").notEqual(\"USA\");\n   * ```\n   *\n   * @param value - The constant value to compare for inequality.\n   * @returns A new `Expression` representing the inequality comparison.\n   */\n  notEqual(value: unknown): BooleanExpression;\n  notEqual(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'not_equal',\n      [this, valueToDefaultExpr(other)],\n      'notEqual'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is less than another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'age' field is less than 'limit'\n   * field(\"age\").lessThan(field('limit'));\n   * ```\n   *\n   * @param experession - The expression to compare for less than.\n   * @returns A new `Expression` representing the less than comparison.\n   */\n  lessThan(experession: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is less than a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'price' field is less than 50\n   * field(\"price\").lessThan(50);\n   * ```\n   *\n   * @param value - The constant value to compare for less than.\n   * @returns A new `Expression` representing the less than comparison.\n   */\n  lessThan(value: unknown): BooleanExpression;\n  lessThan(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'less_than',\n      [this, valueToDefaultExpr(other)],\n      'lessThan'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is less than or equal to another\n   * expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'quantity' field is less than or equal to 20\n   * field(\"quantity\").lessThan(constant(20));\n   * ```\n   *\n   * @param expression - The expression to compare for less than or equal to.\n   * @returns A new `Expression` representing the less than or equal to comparison.\n   */\n  lessThanOrEqual(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is less than or equal to a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'score' field is less than or equal to 70\n   * field(\"score\").lessThan(70);\n   * ```\n   *\n   * @param value - The constant value to compare for less than or equal to.\n   * @returns A new `Expression` representing the less than or equal to comparison.\n   */\n  lessThanOrEqual(value: unknown): BooleanExpression;\n  lessThanOrEqual(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'less_than_or_equal',\n      [this, valueToDefaultExpr(other)],\n      'lessThanOrEqual'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is greater than another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'age' field is greater than the 'limit' field\n   * field(\"age\").greaterThan(field(\"limit\"));\n   * ```\n   *\n   * @param expression - The expression to compare for greater than.\n   * @returns A new `Expression` representing the greater than comparison.\n   */\n  greaterThan(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is greater than a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'price' field is greater than 100\n   * field(\"price\").greaterThan(100);\n   * ```\n   *\n   * @param value - The constant value to compare for greater than.\n   * @returns A new `Expression` representing the greater than comparison.\n   */\n  greaterThan(value: unknown): BooleanExpression;\n  greaterThan(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'greater_than',\n      [this, valueToDefaultExpr(other)],\n      'greaterThan'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is greater than or equal to another\n   * expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1\n   * field(\"quantity\").greaterThanOrEqual(field('requirement').add(1));\n   * ```\n   *\n   * @param expression - The expression to compare for greater than or equal to.\n   * @returns A new `Expression` representing the greater than or equal to comparison.\n   */\n  greaterThanOrEqual(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is greater than or equal to a constant\n   * value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'score' field is greater than or equal to 80\n   * field(\"score\").greaterThanOrEqual(80);\n   * ```\n   *\n   * @param value - The constant value to compare for greater than or equal to.\n   * @returns A new `Expression` representing the greater than or equal to comparison.\n   */\n  greaterThanOrEqual(value: unknown): BooleanExpression;\n  greaterThanOrEqual(other: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'greater_than_or_equal',\n      [this, valueToDefaultExpr(other)],\n      'greaterThanOrEqual'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that concatenates an array expression with one or more other arrays.\n   *\n   * @example\n   * ```typescript\n   * // Combine the 'items' array with another array field.\n   * field(\"items\").arrayConcat(field(\"otherItems\"));\n   * ```\n   * @param secondArray - Second array expression or array literal to concatenate.\n   * @param otherArrays - Optional additional array expressions or array literals to concatenate.\n   * @returns A new `Expression` representing the concatenated array.\n   */\n  arrayConcat(\n    secondArray: Expression | unknown[],\n    ...otherArrays: Array<Expression | unknown[]>\n  ): FunctionExpression {\n    const elements = [secondArray, ...otherArrays];\n    const exprValues = elements.map(value => valueToDefaultExpr(value));\n    return new FunctionExpression(\n      'array_concat',\n      [this, ...exprValues],\n      'arrayConcat'\n    );\n  }\n\n  /**\n   * Creates an expression that checks if an array contains a specific element.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'sizes' array contains the value from the 'selectedSize' field\n   * field(\"sizes\").arrayContains(field(\"selectedSize\"));\n   * ```\n   *\n   * @param expression - The element to search for in the array.\n   * @returns A new `Expression` representing the 'array_contains' comparison.\n   */\n  arrayContains(expression: Expression): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if an array contains a specific value.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'colors' array contains \"red\"\n   * field(\"colors\").arrayContains(\"red\");\n   * ```\n   *\n   * @param value - The element to search for in the array.\n   * @returns A new `Expression` representing the 'array_contains' comparison.\n   */\n  arrayContains(value: unknown): BooleanExpression;\n  arrayContains(element: unknown): BooleanExpression {\n    return new FunctionExpression(\n      'array_contains',\n      [this, valueToDefaultExpr(element)],\n      'arrayContains'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if an array contains all the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'tags' array contains both the value in field \"tag1\" and the literal value \"tag2\"\n   * field(\"tags\").arrayContainsAll([field(\"tag1\"), \"tag2\"]);\n   * ```\n   *\n   * @param values - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_all' comparison.\n   */\n  arrayContainsAll(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if an array contains all the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'tags' array contains both of the values from field \"tag1\" and the literal value \"tag2\"\n   * field(\"tags\").arrayContainsAll(array([field(\"tag1\"), \"tag2\"]));\n   * ```\n   *\n   * @param arrayExpression - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_all' comparison.\n   */\n  arrayContainsAll(arrayExpression: Expression): BooleanExpression;\n  arrayContainsAll(values: unknown[] | Expression): BooleanExpression {\n    const normalizedExpr = Array.isArray(values)\n      ? new ListOfExprs(values.map(valueToDefaultExpr), 'arrayContainsAll')\n      : values;\n    return new FunctionExpression(\n      'array_contains_all',\n      [this, normalizedExpr],\n      'arrayContainsAll'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if an array contains any of the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'categories' array contains either values from field \"cate1\" or \"cate2\"\n   * field(\"categories\").arrayContainsAny([field(\"cate1\"), field(\"cate2\")]);\n   * ```\n   *\n   * @param values - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_any' comparison.\n   */\n  arrayContainsAny(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if an array contains any of the specified elements.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'groups' array contains either the value from the 'userGroup' field\n   * // or the value \"guest\"\n   * field(\"groups\").arrayContainsAny(array([field(\"userGroup\"), \"guest\"]));\n   * ```\n   *\n   * @param arrayExpression - The elements to check for in the array.\n   * @returns A new `Expression` representing the 'array_contains_any' comparison.\n   */\n  arrayContainsAny(arrayExpression: Expression): BooleanExpression;\n  arrayContainsAny(\n    values: Array<unknown | Expression> | Expression\n  ): BooleanExpression {\n    const normalizedExpr = Array.isArray(values)\n      ? new ListOfExprs(values.map(valueToDefaultExpr), 'arrayContainsAny')\n      : values;\n    return new FunctionExpression(\n      'array_contains_any',\n      [this, normalizedExpr],\n      'arrayContainsAny'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that reverses an array.\n   *\n   * @example\n   * ```typescript\n   * // Reverse the value of the 'myArray' field.\n   * field(\"myArray\").arrayReverse();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.\n   */\n  arrayReverse(): FunctionExpression {\n    return new FunctionExpression('array_reverse', [this]);\n  }\n\n  /**\n   * Creates an expression that calculates the length of an array.\n   *\n   * @example\n   * ```typescript\n   * // Get the number of items in the 'cart' array\n   * field(\"cart\").arrayLength();\n   * ```\n   *\n   * @returns A new `Expression` representing the length of the array.\n   */\n  arrayLength(): FunctionExpression {\n    return new FunctionExpression('array_length', [this], 'arrayLength');\n  }\n\n  /**\n   * Creates an expression that checks if this expression is equal to any of the provided values or\n   * expressions.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n   * field(\"category\").equalAny([\"Electronics\", field(\"primaryType\")]);\n   * ```\n   *\n   * @param values - The values or expressions to check against.\n   * @returns A new `Expression` representing the 'IN' comparison.\n   */\n  equalAny(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is equal to any of the provided values or\n   * expressions.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n   * field(\"category\").equalAny(array([\"Electronics\", field(\"primaryType\")]));\n   * ```\n   *\n   * @param arrayExpression - An expression that evaluates to an array of values to check against.\n   * @returns A new `Expression` representing the 'IN' comparison.\n   */\n  equalAny(arrayExpression: Expression): BooleanExpression;\n  equalAny(others: unknown[] | Expression): BooleanExpression {\n    const exprOthers = Array.isArray(others)\n      ? new ListOfExprs(others.map(valueToDefaultExpr), 'equalAny')\n      : others;\n    return new FunctionExpression(\n      'equal_any',\n      [this, exprOthers],\n      'equalAny'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if this expression is not equal to any of the provided values or\n   * expressions.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'status' field is neither \"pending\" nor the value of 'rejectedStatus'\n   * field(\"status\").notEqualAny([\"pending\", field(\"rejectedStatus\")]);\n   * ```\n   *\n   * @param values - The values or expressions to check against.\n   * @returns A new `Expression` representing the 'notEqualAny' comparison.\n   */\n  notEqualAny(values: Array<Expression | unknown>): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses'\n   * field(\"status\").notEqualAny(field('rejectedStatuses'));\n   * ```\n   *\n   * @param arrayExpression - The values or expressions to check against.\n   * @returns A new `Expression` representing the 'notEqualAny' comparison.\n   */\n  notEqualAny(arrayExpression: Expression): BooleanExpression;\n  notEqualAny(others: unknown[] | Expression): BooleanExpression {\n    const exprOthers = Array.isArray(others)\n      ? new ListOfExprs(others.map(valueToDefaultExpr), 'notEqualAny')\n      : others;\n    return new FunctionExpression(\n      'not_equal_any',\n      [this, exprOthers],\n      'notEqualAny'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a field exists in the document.\n   *\n   * @example\n   * ```typescript\n   * // Check if the document has a field named \"phoneNumber\"\n   * field(\"phoneNumber\").exists();\n   * ```\n   *\n   * @returns A new `Expression` representing the 'exists' check.\n   */\n  exists(): BooleanExpression {\n    return new FunctionExpression('exists', [this], 'exists').asBoolean();\n  }\n\n  /**\n   * Creates an expression that calculates the character length of a string in UTF-8.\n   *\n   * @example\n   * ```typescript\n   * // Get the character length of the 'name' field in its UTF-8 form.\n   * field(\"name\").charLength();\n   * ```\n   *\n   * @returns A new `Expression` representing the length of the string.\n   */\n  charLength(): FunctionExpression {\n    return new FunctionExpression('char_length', [this], 'charLength');\n  }\n\n  /**\n   * Creates an expression that performs a case-sensitive string comparison.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'title' field contains the word \"guide\" (case-sensitive)\n   * field(\"title\").like(\"%guide%\");\n   * ```\n   *\n   * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n   * @returns A new `Expression` representing the 'like' comparison.\n   */\n  like(pattern: string): BooleanExpression;\n\n  /**\n   * Creates an expression that performs a case-sensitive string comparison.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'title' field contains the word \"guide\" (case-sensitive)\n   * field(\"title\").like(\"%guide%\");\n   * ```\n   *\n   * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n   * @returns A new `Expression` representing the 'like' comparison.\n   */\n  like(pattern: Expression): BooleanExpression;\n  like(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'like',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'like'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string contains a specified regular expression as a\n   * substring.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains \"example\" (case-insensitive)\n   * field(\"description\").regexContains(\"(?i)example\");\n   * ```\n   *\n   * @param pattern - The regular expression to use for the search.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  regexContains(pattern: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string contains a specified regular expression as a\n   * substring.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains the regular expression stored in field 'regex'\n   * field(\"description\").regexContains(field(\"regex\"));\n   * ```\n   *\n   * @param pattern - The regular expression to use for the search.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  regexContains(pattern: Expression): BooleanExpression;\n  regexContains(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'regex_contains',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexContains'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that returns the first substring of a string expression that matches\n   * a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract the domain from an email address\n   * field(\"email\").regexFind(\"@.+\")\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n   */\n  regexFind(pattern: string): FunctionExpression;\n\n  /**\n   * Creates an expression that returns the first substring of a string expression that matches\n   * a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract the domain from an email address\n   * field(\"email\").regexFind(field(\"domain\"))\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n   */\n  regexFind(pattern: Expression): FunctionExpression;\n  regexFind(stringOrExpr: string | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'regex_find',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexFind'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that evaluates to a list of all substrings in this string expression that\n   * match a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract all hashtags from a post content field\n   * field(\"content\").regexFindAll(\"#[A-Za-z0-9_]+\")\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} that evaluates to an array of matched substrings.\n   */\n  regexFindAll(pattern: string): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that evaluates to a list of all substrings in this string expression that\n   * match a specified regular expression.\n   *\n   * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n   *\n   * @example\n   * ```typescript\n   * // Extract all names from a post content field\n   * field(\"content\").regexFindAll(field(\"names\"))\n   * ```\n   *\n   * @param pattern - The regular expression to search for.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} that evaluates to an array of matched substrings.\n   */\n  regexFindAll(pattern: Expression): FunctionExpression;\n  regexFindAll(stringOrExpr: string | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'regex_find_all',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexFindAll'\n    );\n  }\n\n  /**\n   * Creates an expression that checks if a string matches a specified regular expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'email' field matches a valid email pattern\n   * field(\"email\").regexMatch(\"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}\");\n   * ```\n   *\n   * @param pattern - The regular expression to use for the match.\n   * @returns A new `Expression` representing the regular expression match.\n   */\n  regexMatch(pattern: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string matches a specified regular expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'email' field matches a regular expression stored in field 'regex'\n   * field(\"email\").regexMatch(field(\"regex\"));\n   * ```\n   *\n   * @param pattern - The regular expression to use for the match.\n   * @returns A new `Expression` representing the regular expression match.\n   */\n  regexMatch(pattern: Expression): BooleanExpression;\n  regexMatch(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'regex_match',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'regexMatch'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string contains a specified substring.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains \"example\".\n   * field(\"description\").stringContains(\"example\");\n   * ```\n   *\n   * @param substring - The substring to search for.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  stringContains(substring: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string contains the string represented by another expression.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'description' field contains the value of the 'keyword' field.\n   * field(\"description\").stringContains(field(\"keyword\"));\n   * ```\n   *\n   * @param expr - The expression representing the substring to search for.\n   * @returns A new `Expression` representing the 'contains' comparison.\n   */\n  stringContains(expr: Expression): BooleanExpression;\n  stringContains(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'string_contains',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'stringContains'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string starts with a given prefix.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'name' field starts with \"Mr.\"\n   * field(\"name\").startsWith(\"Mr.\");\n   * ```\n   *\n   * @param prefix - The prefix to check for.\n   * @returns A new `Expression` representing the 'starts with' comparison.\n   */\n  startsWith(prefix: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string starts with a given prefix (represented as an\n   * expression).\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'fullName' field starts with the value of the 'firstName' field\n   * field(\"fullName\").startsWith(field(\"firstName\"));\n   * ```\n   *\n   * @param prefix - The prefix expression to check for.\n   * @returns A new `Expression` representing the 'starts with' comparison.\n   */\n  startsWith(prefix: Expression): BooleanExpression;\n  startsWith(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'starts_with',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'startsWith'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that checks if a string ends with a given postfix.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'filename' field ends with \".txt\"\n   * field(\"filename\").endsWith(\".txt\");\n   * ```\n   *\n   * @param suffix - The postfix to check for.\n   * @returns A new `Expression` representing the 'ends with' comparison.\n   */\n  endsWith(suffix: string): BooleanExpression;\n\n  /**\n   * Creates an expression that checks if a string ends with a given postfix (represented as an\n   * expression).\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'url' field ends with the value of the 'extension' field\n   * field(\"url\").endsWith(field(\"extension\"));\n   * ```\n   *\n   * @param suffix - The postfix expression to check for.\n   * @returns A new `Expression` representing the 'ends with' comparison.\n   */\n  endsWith(suffix: Expression): BooleanExpression;\n  endsWith(stringOrExpr: string | Expression): BooleanExpression {\n    return new FunctionExpression(\n      'ends_with',\n      [this, valueToDefaultExpr(stringOrExpr)],\n      'endsWith'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that converts a string to lowercase.\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'name' field to lowercase\n   * field(\"name\").toLower();\n   * ```\n   *\n   * @returns A new `Expression` representing the lowercase string.\n   */\n  toLower(): FunctionExpression {\n    return new FunctionExpression('to_lower', [this], 'toLower');\n  }\n\n  /**\n   * Creates an expression that converts a string to uppercase.\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'title' field to uppercase\n   * field(\"title\").toUpper();\n   * ```\n   *\n   * @returns A new `Expression` representing the uppercase string.\n   */\n  toUpper(): FunctionExpression {\n    return new FunctionExpression('to_upper', [this], 'toUpper');\n  }\n\n  /**\n   * Creates an expression that removes leading and trailing characters from a string or byte array.\n   *\n   * @example\n   * ```typescript\n   * // Trim whitespace from the 'userInput' field\n   * field(\"userInput\").trim();\n   *\n   * // Trim quotes from the 'userInput' field\n   * field(\"userInput\").trim('\"');\n   * ```\n   * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be\n   * trimmed from the input. If not specified, then whitespace will be trimmed.\n   * @returns A new `Expression` representing the trimmed string or byte array.\n   */\n  trim(valueToTrim?: string | Expression | Bytes): FunctionExpression {\n    const args: Expression[] = [this];\n    if (valueToTrim) {\n      args.push(valueToDefaultExpr(valueToTrim));\n    }\n    return new FunctionExpression('trim', args, 'trim');\n  }\n\n  /**\n   * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.\n   *\n   * @example\n   * ```typescript\n   * // Trim whitespace from the beginning of the 'userInput' field\n   * field(\"userInput\").ltrim();\n   *\n   * // Trim quotes from the beginning of the 'userInput' field\n   * field(\"userInput\").ltrim('\"');\n   * ```\n   *\n   * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n   * If not specified, whitespace will be trimmed.\n   * @returns A new `Expression` representing the trimmed string.\n   */\n  ltrim(valueToTrim?: string | Expression | Bytes): FunctionExpression {\n    const args: Expression[] = [this];\n    if (valueToTrim) {\n      args.push(valueToDefaultExpr(valueToTrim));\n    }\n    return new FunctionExpression('ltrim', args, 'ltrim');\n  }\n\n  /**\n   * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.\n   *\n   * @example\n   * ```typescript\n   * // Trim whitespace from the end of the 'userInput' field\n   * field(\"userInput\").rtrim();\n   *\n   * // Trim quotes from the end of the 'userInput' field\n   * field(\"userInput\").rtrim('\"');\n   * ```\n   *\n   * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n   * If not specified, whitespace will be trimmed.\n   * @returns A new `Expression` representing the trimmed string or byte array.\n   */\n  rtrim(valueToTrim?: string | Expression | Bytes): FunctionExpression {\n    const args: Expression[] = [this];\n    if (valueToTrim) {\n      args.push(valueToDefaultExpr(valueToTrim));\n    }\n    return new FunctionExpression('rtrim', args, 'rtrim');\n  }\n\n  /**\n   * Creates an expression that returns the data type of this expression's result, as a string.\n   *\n   * @remarks\n   * This is evaluated on the backend. This means:\n   * 1. Generic typed elements (like `array<string>`) evaluate strictly to the primitive `'array'`.\n   * 2. Any custom `FirestoreDataConverter` mappings are ignored.\n   * 3. For numeric values, the backend does not yield the JavaScript `\"number\"` type; it evaluates\n   *    precisely as `\"int64\"` or `\"float64\"`.\n   * 4. For date or timestamp objects, the backend evaluates to `\"timestamp\"`.\n   *\n   * @example\n   * ```typescript\n   * // Get the data type of the value in field 'title'\n   * field('title').type()\n   * ```\n   *\n   * @returns A new `Expression` representing the data type.\n   */\n  type(): FunctionExpression {\n    return new FunctionExpression('type', [this]);\n  }\n\n  /**\n   * Creates an expression that checks if the result of this expression is of the given type.\n   *\n   * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.\n   * Supported values for `type` are:\n   * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,\n   * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,\n   * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.\n   *\n   * @example\n   * ```typescript\n   * // Check if the 'price' field is specifically an integer (not just 'number')\n   * field('price').isType('int64');\n   * ```\n   *\n   * @param type - The type to check for.\n   * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise.\n   */\n  isType(type: string): BooleanExpression {\n    return new FunctionExpression(\n      'is_type',\n      [this, constant(type)],\n      'isType'\n    ).asBoolean();\n  }\n\n  /**\n   * Creates an expression that concatenates string expressions together.\n   *\n   * @example\n   * ```typescript\n   * // Combine the 'firstName', \" \", and 'lastName' fields into a single string\n   * field(\"firstName\").stringConcat(constant(\" \"), field(\"lastName\"));\n   * ```\n   *\n   * @param secondString - The additional expression or string literal to concatenate.\n   * @param otherStrings - Optional additional expressions or string literals to concatenate.\n   * @returns A new `Expression` representing the concatenated string.\n   */\n  stringConcat(\n    secondString: Expression | string,\n    ...otherStrings: Array<Expression | string>\n  ): FunctionExpression {\n    const elements = [secondString, ...otherStrings];\n    const exprs = elements.map(valueToDefaultExpr);\n    return new FunctionExpression(\n      'string_concat',\n      [this, ...exprs],\n      'stringConcat'\n    );\n  }\n\n  /**\n   * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.\n   *\n   * @example\n   * ```typescript\n   * // Find the index of \"foo\" in the 'text' field\n   * field(\"text\").stringIndexOf(\"foo\");\n   * ```\n   *\n   * @param search - The substring or byte sequence to search for.\n   * @returns A new `Expression` representing the index of the first occurrence.\n   */\n  stringIndexOf(search: string | Expression | Bytes): FunctionExpression {\n    return new FunctionExpression(\n      'string_index_of',\n      [this, valueToDefaultExpr(search)],\n      'stringIndexOf'\n    );\n  }\n\n  /**\n   * Creates an expression that repeats a string or byte array a specified number of times.\n   *\n   * @example\n   * ```typescript\n   * // Repeat the 'label' field 3 times\n   * field(\"label\").stringRepeat(3);\n   * ```\n   *\n   * @param repetitions - The number of times to repeat the string or byte array.\n   * @returns A new `Expression` representing the repeated string or byte array.\n   */\n  stringRepeat(repetitions: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'string_repeat',\n      [this, valueToDefaultExpr(repetitions)],\n      'stringRepeat'\n    );\n  }\n\n  /**\n   * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.\n   *\n   * @example\n   * ```typescript\n   * // Replace all occurrences of \"foo\" with \"bar\" in the 'text' field\n   * field(\"text\").stringReplaceAll(\"foo\", \"bar\");\n   * ```\n   *\n   * @param find - The substring or byte sequence to search for.\n   * @param replacement - The replacement string or byte sequence.\n   * @returns A new `Expression` representing the string or byte array with replacements.\n   */\n  stringReplaceAll(\n    find: string | Expression | Bytes,\n    replacement: string | Expression | Bytes\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'string_replace_all',\n      [this, valueToDefaultExpr(find), valueToDefaultExpr(replacement)],\n      'stringReplaceAll'\n    );\n  }\n\n  /**\n   * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.\n   *\n   * @example\n   * ```typescript\n   * // Replace the first occurrence of \"foo\" with \"bar\" in the 'text' field\n   * field(\"text\").stringReplaceOne(\"foo\", \"bar\");\n   * ```\n   *\n   * @param find - The substring or byte sequence to search for.\n   * @param replacement - The replacement string or byte sequence.\n   * @returns A new `Expression` representing the string or byte array with the replacement.\n   */\n  stringReplaceOne(\n    find: string | Expression | Bytes,\n    replacement: string | Expression | Bytes\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'string_replace_one',\n      [this, valueToDefaultExpr(find), valueToDefaultExpr(replacement)],\n      'stringReplaceOne'\n    );\n  }\n\n  /**\n   * Creates an expression that concatenates expression results together.\n   *\n   * @example\n   * ```typescript\n   * // Combine the 'firstName', ' ', and 'lastName' fields into a single value.\n   * field(\"firstName\").concat(constant(\" \"), field(\"lastName\"));\n   * ```\n   *\n   * @param second - The additional expression or literal to concatenate.\n   * @param others - Optional additional expressions or literals to concatenate.\n   * @returns A new `Expression` representing the concatenated value.\n   */\n  concat(\n    second: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    const elements = [second, ...others];\n    const exprs = elements.map(valueToDefaultExpr);\n    return new FunctionExpression('concat', [this, ...exprs], 'concat');\n  }\n\n  /**\n   * Creates an expression that reverses this string expression.\n   *\n   * @example\n   * ```typescript\n   * // Reverse the value of the 'myString' field.\n   * field(\"myString\").reverse();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n   */\n  reverse(): FunctionExpression {\n    return new FunctionExpression('reverse', [this], 'reverse');\n  }\n\n  /**\n   * Filters the array using a provided alias and predicate expression.\n   *\n   * @example\n   * ```typescript\n   * // Filter the 'items' array to only include those where the 'price' is greater than 10\n   * field(\"items\").arrayFilter('item', greaterThan(variable('item.price'), 10));\n   * ```\n   *\n   * @param alias - The variable name to use for each element.\n   * @param filter - The predicate boolean expression to filter by.\n   * @returns A new `Expression` representing the filtered array.\n   */\n  arrayFilter(alias: string, filter: BooleanExpression): FunctionExpression {\n    return new FunctionExpression(\n      'array_filter',\n      [this, valueToDefaultExpr(alias), filter],\n      'arrayFilter'\n    );\n  }\n\n  /**\n   * Creates an expression that applies a provided transformation to each element in an array.\n   *\n   * @example\n   * ```typescript\n   * // Transform the 'scores' array by multiplying each score by 10\n   * field(\"scores\").arrayTransform(\"score\", multiply(variable(\"score\"), 10));\n   * ```\n   *\n   * @param elementAlias - The variable name to use for each element.\n   * @param transform - The lambda expression used to transform the elements.\n   * @returns A new `Expression` representing the arrayTransform operation.\n   */\n  arrayTransform(\n    elementAlias: string,\n    transform: Expression\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'array_transform',\n      [this, valueToDefaultExpr(elementAlias), transform],\n      'arrayTransform'\n    );\n  }\n\n  /**\n   * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.\n   *\n   * @example\n   * ```typescript\n   * // Transform the 'scores' array by adding the index to each score\n   * field(\"scores\").arrayTransformWithIndex(\"score\", \"i\", add(variable(\"score\"), variable(\"i\")));\n   * ```\n   *\n   * @param elementAlias - The variable name to use for each element.\n   * @param indexAlias - The variable name to use for the current index.\n   * @param transform - The lambda expression used to transform the elements.\n   * @returns A new `Expression` representing the arrayTransformWithIndex operation.\n   */\n  arrayTransformWithIndex(\n    elementAlias: string,\n    indexAlias: string,\n    transform: Expression\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'array_transform',\n      [\n        this,\n        valueToDefaultExpr(elementAlias),\n        valueToDefaultExpr(indexAlias),\n        transform\n      ],\n      'arrayTransformWithIndex'\n    );\n  }\n\n  /**\n   * Returns a subset of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get 5 elements from the 'items' array starting from index 2\n   * field(\"items\").arraySlice(2, 5);\n   *\n   * // Get n number of elements from the 'items' array starting from index 2\n   * field(\"items\").arraySlice(2, field(\"count\"));\n   * ```\n   *\n   * @param offset - The starting offset.\n   * @param length - The optional length of the slice.\n   * @returns A new `Expression` representing the sliced array.\n   */\n  arraySlice(\n    offset: number | Expression,\n    length?: number | Expression\n  ): FunctionExpression {\n    const args: Expression[] = [this, valueToDefaultExpr(offset)];\n    if (length !== undefined) {\n      args.push(valueToDefaultExpr(length));\n    }\n    return new FunctionExpression('array_slice', args, 'arraySlice');\n  }\n\n  /**\n   * Returns the first element of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the first element of the 'myArray' field.\n   * field(\"myArray\").arrayFirst();\n   * ```\n   *\n   * @returns A new `Expression` representing the first element.\n   */\n  arrayFirst(): FunctionExpression {\n    return new FunctionExpression('array_first', [this], 'arrayFirst');\n  }\n\n  /**\n   * Returns the first `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the first 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayFirstN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the first `n` elements.\n   */\n  arrayFirstN(n: number): FunctionExpression;\n\n  /**\n   * Returns the first `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the first n elements of the 'myArray' field.\n   * field(\"myArray\").arrayFirstN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the first `n` elements.\n   */\n  arrayFirstN(n: Expression): FunctionExpression;\n  arrayFirstN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_first_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayFirstN'\n    );\n  }\n\n  /**\n   * Returns the last element of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the last element of the 'myArray' field.\n   * field(\"myArray\").arrayLast();\n   * ```\n   *\n   * @returns A new `Expression` representing the last element.\n   */\n  arrayLast(): FunctionExpression {\n    return new FunctionExpression('array_last', [this], 'arrayLast');\n  }\n\n  /**\n   * Returns the last `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the last 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayLastN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the last `n` elements.\n   */\n  arrayLastN(n: number): FunctionExpression;\n\n  /**\n   * Returns the last `n` elements of the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the last n elements of the 'myArray' field.\n   * field(\"myArray\").arrayLastN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the last `n` elements.\n   */\n  arrayLastN(n: Expression): FunctionExpression;\n  arrayLastN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_last_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayLastN'\n    );\n  }\n\n  /**\n   * Returns the maximum value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the maximum value of the 'myArray' field.\n   * field(\"myArray\").arrayMaximum();\n   * ```\n   *\n   * @returns A new `Expression` representing the maximum value.\n   */\n  arrayMaximum(): FunctionExpression {\n    return new FunctionExpression('maximum', [this], 'arrayMaximum');\n  }\n\n  /**\n   * Returns the largest `n` elements of the array.\n   *\n   * Note: Returns the n largest non-null elements in the array, in descending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the largest 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayMaximumN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the largest `n` elements.\n   */\n  arrayMaximumN(n: number): FunctionExpression;\n\n  /**\n   * Returns the largest `n` elements of the array.\n   *\n   * Note: Returns the n largest non-null elements in the array, in descending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the largest n elements of the 'myArray' field.\n   * field(\"myArray\").arrayMaximumN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the largest `n` elements.\n   */\n  arrayMaximumN(n: Expression): FunctionExpression;\n  arrayMaximumN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'maximum_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayMaximumN'\n    );\n  }\n\n  /**\n   * Returns the minimum value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get the minimum value of the 'myArray' field.\n   * field(\"myArray\").arrayMinimum();\n   * ```\n   *\n   * @returns A new `Expression` representing the minimum value.\n   */\n  arrayMinimum(): FunctionExpression {\n    return new FunctionExpression('minimum', [this], 'arrayMinimum');\n  }\n\n  /**\n   * Returns the smallest `n` elements of the array.\n   *\n   * Note: Returns the n smallest non-null elements in the array, in ascending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the smallest 3 elements of the 'myArray' field.\n   * field(\"myArray\").arrayMinimumN(3);\n   * ```\n   *\n   * @param n - The number of elements to return.\n   * @returns A new `Expression` representing the smallest `n` elements.\n   */\n  arrayMinimumN(n: number): FunctionExpression;\n\n  /**\n   * Returns the smallest `n` elements of the array.\n   *\n   * Note: Returns the n smallest non-null elements in the array, in ascending\n   * order. This does not use a stable sort, meaning the order of equivalent\n   * elements is undefined.\n   *\n   * @example\n   * ```typescript\n   * // Get the smallest n elements of the 'myArray' field.\n   * field(\"myArray\").arrayMinimumN(field(\"count\"));\n   * ```\n   *\n   * @param n - An expression evaluating to the number of elements to return.\n   * @returns A new `Expression` representing the smallest `n` elements.\n   */\n  arrayMinimumN(n: Expression): FunctionExpression;\n  arrayMinimumN(n: number | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'minimum_n',\n      [this, valueToDefaultExpr(n)],\n      'arrayMinimumN'\n    );\n  }\n\n  /**\n   * Returns the first index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the first index of the value 3 in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOf(3);\n   * ```\n   *\n   * @param search - The value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayIndexOf(search: unknown): FunctionExpression;\n\n  /**\n   * Returns the first index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the first index of the value in 'searchVal' field in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOf(field(\"searchVal\"));\n   * ```\n   *\n   * @param search - An expression evaluating to the value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayIndexOf(search: Expression): FunctionExpression;\n  arrayIndexOf(search: unknown | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_index_of',\n      [this, valueToDefaultExpr(search), valueToDefaultExpr('first')],\n      'arrayIndexOf'\n    );\n  }\n\n  /**\n   * Returns the last index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the last index of the value 3 in the 'myArray' field.\n   * field(\"myArray\").arrayLastIndexOf(3);\n   * ```\n   *\n   * @param search - The value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayLastIndexOf(search: unknown): FunctionExpression;\n\n  /**\n   * Returns the last index of the search value in the array, or -1 if not found.\n   *\n   * @example\n   * ```typescript\n   * // Get the last index of the value in 'searchVal' field in the 'myArray' field.\n   * field(\"myArray\").arrayLastIndexOf(field(\"searchVal\"));\n   * ```\n   *\n   * @param search - An expression evaluating to the value to search for.\n   * @returns A new `Expression` representing the index.\n   */\n  arrayLastIndexOf(search: Expression): FunctionExpression;\n  arrayLastIndexOf(search: unknown | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_index_of',\n      [this, valueToDefaultExpr(search), valueToDefaultExpr('last')],\n      'arrayLastIndexOf'\n    );\n  }\n\n  /**\n   * Returns all indices of the search value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get all indices of the value 3 in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOfAll(3);\n   * ```\n   *\n   * @param search - The value to search for.\n   * @returns A new `Expression` representing the indices.\n   */\n  arrayIndexOfAll(search: unknown): FunctionExpression;\n\n  /**\n   * Returns all indices of the search value in the array.\n   *\n   * @example\n   * ```typescript\n   * // Get all indices of the value in 'searchVal' field in the 'myArray' field.\n   * field(\"myArray\").arrayIndexOfAll(field(\"searchVal\"));\n   * ```\n   *\n   * @param search - An expression evaluating to the value to search for.\n   * @returns A new `Expression` representing the indices.\n   */\n  arrayIndexOfAll(search: Expression): FunctionExpression;\n  arrayIndexOfAll(search: unknown | Expression): FunctionExpression {\n    return new FunctionExpression(\n      'array_index_of_all',\n      [this, valueToDefaultExpr(search)],\n      'arrayIndexOfAll'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the length of this string expression in bytes.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the length of the 'myString' field in bytes.\n   * field(\"myString\").byteLength();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.\n   */\n  byteLength(): FunctionExpression {\n    return new FunctionExpression('byte_length', [this], 'byteLength');\n  }\n\n  /**\n   * Creates an expression that computes the ceiling of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the ceiling of the 'price' field.\n   * field(\"price\").ceil();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.\n   */\n  ceil(): FunctionExpression {\n    return new FunctionExpression('ceil', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the floor of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the floor of the 'price' field.\n   * field(\"price\").floor();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.\n   */\n  floor(): FunctionExpression {\n    return new FunctionExpression('floor', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the absolute value of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the absolute value of the 'price' field.\n   * field(\"price\").abs();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.\n   */\n  abs(): FunctionExpression {\n    return new FunctionExpression('abs', [this]);\n  }\n\n  /**\n   * Creates an expression that computes e to the power of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Compute e to the power of the 'value' field.\n   * field(\"value\").exp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.\n   */\n  exp(): FunctionExpression {\n    return new FunctionExpression('exp', [this]);\n  }\n\n  /**\n   * Accesses a value from a map (object) field using the provided key.\n   *\n   * @example\n   * ```typescript\n   * // Get the 'city' value from the 'address' map field\n   * field(\"address\").mapGet(\"city\");\n   * ```\n   *\n   * @param subfield - The key to access in the map.\n   * @returns A new `Expression` representing the value associated with the given key in the map.\n   */\n  mapGet(subfield: string): FunctionExpression {\n    return new FunctionExpression(\n      'map_get',\n      [this, constant(subfield)],\n      'mapGet'\n    );\n  }\n\n  /**\n   * Creates an expression that returns a new map with the specified entries added or updated.\n   *\n   * @remarks\n   * Note that `mapSet` only performs shallow updates to the map. Setting a value to `null`\n   * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.\n   *\n   * @example\n   * ```typescript\n   * // Set the 'city' to \"San Francisco\" in the 'address' map\n   * field(\"address\").mapSet(\"city\", \"San Francisco\");\n   * ```\n   *\n   * @param key - The key to set. Must be a string or a constant string expression.\n   * @param value - The value to set.\n   * @param moreKeyValues - Additional key-value pairs to set.\n   * @returns A new `Expression` representing the map with the entries set.\n   */\n  mapSet(\n    key: string | Expression,\n    value: unknown,\n    ...moreKeyValues: unknown[]\n  ): FunctionExpression {\n    const args = [\n      this,\n      valueToDefaultExpr(key),\n      valueToDefaultExpr(value),\n      ...moreKeyValues.map(valueToDefaultExpr)\n    ];\n    return new FunctionExpression('map_set', args, 'mapSet');\n  }\n\n  /**\n   * Creates an expression that returns the keys of a map.\n   *\n   * @remarks\n   * While the backend generally preserves insertion order, relying on the\n   * order of the output array is not guaranteed and should be avoided.\n   *\n   * @example\n   * ```typescript\n   * // Get the keys of the 'address' map\n   * field(\"address\").mapKeys();\n   * ```\n   *\n   * @returns A new `Expression` representing the keys of the map.\n   */\n  mapKeys(): FunctionExpression {\n    return new FunctionExpression('map_keys', [this], 'mapKeys');\n  }\n\n  /**\n   * Creates an expression that returns the values of a map.\n   *\n   * @remarks\n   * While the backend generally preserves insertion order, relying on the\n   * order of the output array is not guaranteed and should be avoided.\n   *\n   * @example\n   * ```typescript\n   * // Get the values of the 'address' map\n   * field(\"address\").mapValues();\n   * ```\n   *\n   * @returns A new `Expression` representing the values of the map.\n   */\n  mapValues(): FunctionExpression {\n    return new FunctionExpression('map_values', [this], 'mapValues');\n  }\n\n  /**\n   * Creates an expression that returns the entries of a map as an array of maps,\n   * where each map contains a `\"k\"` property for the key and a `\"v\"` property for the value.\n   * For example: `[{ k: \"key1\", v: \"value1\" }, ...]`.\n   *\n   * @example\n   * ```typescript\n   * // Get the entries of the 'address' map\n   * field(\"address\").mapEntries();\n   * ```\n   *\n   * @returns A new `Expression` representing the entries of the map.\n   */\n  mapEntries(): FunctionExpression {\n    return new FunctionExpression('map_entries', [this], 'mapEntries');\n  }\n\n  /**\n   * @public\n   * Creates an expression that returns the value of a field from the document that results from the evaluation of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Get the value of the \"city\" field in the \"address\" document.\n   * field(\"address\").getField(\"city\")\n   * ```\n   *\n   * @param key The field to access in the document.\n   * @returns A new `Expression` representing the value of the field in the document.\n   */\n  getField(key: string | Expression): Expression {\n    return new FunctionExpression(\n      'get_field',\n      [this, valueToDefaultExpr(key)],\n      'get_field'\n    );\n  }\n\n  /**\n   * Creates an aggregation that counts the number of stage inputs with valid evaluations of the\n   * expression or field.\n   *\n   * @example\n   * ```typescript\n   * // Count the total number of products\n   * field(\"productId\").count().as(\"totalProducts\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'count' aggregation.\n   */\n  count(): AggregateFunction {\n    return AggregateFunction._create('count', [this], 'count');\n  }\n\n  /**\n   * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the total revenue from a set of orders\n   * field(\"orderAmount\").sum().as(\"totalRevenue\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'sum' aggregation.\n   */\n  sum(): AggregateFunction {\n    return AggregateFunction._create('sum', [this], 'sum');\n  }\n\n  /**\n   * Creates an aggregation that calculates the average (mean) of a numeric field across multiple\n   * stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the average age of users\n   * field(\"age\").average().as(\"averageAge\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'average' aggregation.\n   */\n  average(): AggregateFunction {\n    return AggregateFunction._create('average', [this], 'average');\n  }\n\n  /**\n   * Creates an aggregation that finds the minimum value of a field across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the lowest price of all products\n   * field(\"price\").minimum().as(\"lowestPrice\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'minimum' aggregation.\n   */\n  minimum(): AggregateFunction {\n    return AggregateFunction._create('minimum', [this], 'minimum');\n  }\n\n  /**\n   * Creates an aggregation that finds the maximum value of a field across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the highest score in a leaderboard\n   * field(\"score\").maximum().as(\"highestScore\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'maximum' aggregation.\n   */\n  maximum(): AggregateFunction {\n    return AggregateFunction._create('maximum', [this], 'maximum');\n  }\n\n  /**\n   * Creates an aggregation that finds the first value of an expression across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the first value of the 'rating' field\n   * field(\"rating\").first().as(\"firstRating\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'first' aggregation.\n   */\n  first(): AggregateFunction {\n    return AggregateFunction._create('first', [this], 'first');\n  }\n\n  /**\n   * Creates an aggregation that finds the last value of an expression across multiple stage inputs.\n   *\n   * @example\n   * ```typescript\n   * // Find the last value of the 'rating' field\n   * field(\"rating\").last().as(\"lastRating\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'last' aggregation.\n   */\n  last(): AggregateFunction {\n    return AggregateFunction._create('last', [this], 'last');\n  }\n\n  /**\n   * Creates an aggregation that collects all values of an expression across multiple stage inputs\n   * into an array.\n   *\n   * @remarks\n   * If the expression resolves to an absent value, it is converted to `null`.\n   * The order of elements in the output array is not stable and shouldn't be relied upon.\n   *\n   * @example\n   * ```typescript\n   * // Collect all tags from books into an array\n   * field(\"tags\").arrayAgg().as(\"allTags\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'array_agg' aggregation.\n   */\n  arrayAgg(): AggregateFunction {\n    return AggregateFunction._create('array_agg', [this], 'arrayAgg');\n  }\n\n  /**\n   * Creates an aggregation that collects all distinct values of an expression across multiple stage\n   * inputs into an array.\n   *\n   * @remarks\n   * If the expression resolves to an absent value, it is converted to `null`.\n   * The order of elements in the output array is not stable and shouldn't be relied upon.\n   *\n   * @example\n   * ```typescript\n   * // Collect all distinct tags from books into an array\n   * field(\"tags\").arrayAggDistinct().as(\"allDistinctTags\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'array_agg_distinct' aggregation.\n   */\n  arrayAggDistinct(): AggregateFunction {\n    return AggregateFunction._create(\n      'array_agg_distinct',\n      [this],\n      'arrayAggDistinct'\n    );\n  }\n\n  /**\n   * Creates an aggregation that counts the number of distinct values of the expression or field.\n   *\n   * @example\n   * ```typescript\n   * // Count the distinct number of products\n   * field(\"productId\").countDistinct().as(\"distinctProducts\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.\n   */\n  countDistinct(): AggregateFunction {\n    return AggregateFunction._create('count_distinct', [this], 'countDistinct');\n  }\n\n  /**\n   * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering.\n   *\n   * @example\n   * ```typescript\n   * // Returns the larger value between the 'timestamp' field and the current timestamp.\n   * field(\"timestamp\").logicalMaximum(currentTimestamp());\n   * ```\n   *\n   * @param second - The second expression or literal to compare with.\n   * @param others - Optional additional expressions or literals to compare with.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.\n   */\n  logicalMaximum(\n    second: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    const values = [second, ...others];\n    return new FunctionExpression(\n      'maximum',\n      [this, ...values.map(valueToDefaultExpr)],\n      'logicalMaximum'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering.\n   *\n   * @example\n   * ```typescript\n   * // Returns the smaller value between the 'timestamp' field and the current timestamp.\n   * field(\"timestamp\").logicalMinimum(currentTimestamp());\n   * ```\n   *\n   * @param second - The second expression or literal to compare with.\n   * @param others - Optional additional expressions or literals to compare with.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.\n   */\n  logicalMinimum(\n    second: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    const values = [second, ...others];\n    return new FunctionExpression(\n      'minimum',\n      [this, ...values.map(valueToDefaultExpr)],\n      'minimum'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression.\n   *\n   * @example\n   * ```typescript\n   * // Get the vector length (dimension) of the field 'embedding'.\n   * field(\"embedding\").vectorLength();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the vector.\n   */\n  vectorLength(): FunctionExpression {\n    return new FunctionExpression('vector_length', [this], 'vectorLength');\n  }\n\n  /**\n   * Calculates the cosine distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field\n   * field(\"userVector\").cosineDistance(field(\"itemVector\"));\n   * ```\n   *\n   * @param vectorExpression - The other vector (represented as an Expression) to compare against.\n   * @returns A new `Expression` representing the cosine distance between the two vectors.\n   */\n  cosineDistance(vectorExpression: Expression): FunctionExpression;\n  /**\n   * Calculates the Cosine distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the Cosine distance between the 'location' field and a target location\n   * field(\"location\").cosineDistance(new VectorValue([37.7749, -122.4194]));\n   * ```\n   *\n   * @param vector - The other vector (as a VectorValue) to compare against.\n   * @returns A new `Expression` representing the Cosine* distance between the two vectors.\n   */\n  cosineDistance(vector: VectorValue | number[]): FunctionExpression;\n  cosineDistance(\n    other: Expression | VectorValue | number[]\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'cosine_distance',\n      [this, vectorToExpr(other)],\n      'cosineDistance'\n    );\n  }\n\n  /**\n   * Calculates the dot product between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the dot product between a feature vector and a target vector\n   * field(\"features\").dotProduct([0.5, 0.8, 0.2]);\n   * ```\n   *\n   * @param vectorExpression - The other vector (as an array of numbers) to calculate with.\n   * @returns A new `Expression` representing the dot product between the two vectors.\n   */\n  dotProduct(vectorExpression: Expression): FunctionExpression;\n\n  /**\n   * Calculates the dot product between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the dot product between a feature vector and a target vector\n   * field(\"features\").dotProduct(new VectorValue([0.5, 0.8, 0.2]));\n   * ```\n   *\n   * @param vector - The other vector (as an array of numbers) to calculate with.\n   * @returns A new `Expression` representing the dot product between the two vectors.\n   */\n  dotProduct(vector: VectorValue | number[]): FunctionExpression;\n  dotProduct(other: Expression | VectorValue | number[]): FunctionExpression {\n    return new FunctionExpression(\n      'dot_product',\n      [this, vectorToExpr(other)],\n      'dotProduct'\n    );\n  }\n\n  /**\n   * Calculates the Euclidean distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the Euclidean distance between the 'location' field and a target location\n   * field(\"location\").euclideanDistance([37.7749, -122.4194]);\n   * ```\n   *\n   * @param vectorExpression - The other vector (as an array of numbers) to calculate with.\n   * @returns A new `Expression` representing the Euclidean distance between the two vectors.\n   */\n  euclideanDistance(vectorExpression: Expression): FunctionExpression;\n\n  /**\n   * Calculates the Euclidean distance between two vectors.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the Euclidean distance between the 'location' field and a target location\n   * field(\"location\").euclideanDistance(new VectorValue([37.7749, -122.4194]));\n   * ```\n   *\n   * @param vector - The other vector (as a VectorValue) to compare against.\n   * @returns A new `Expression` representing the Euclidean distance between the two vectors.\n   */\n  euclideanDistance(vector: VectorValue | number[]): FunctionExpression;\n  euclideanDistance(\n    other: Expression | VectorValue | number[]\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'euclidean_distance',\n      [this, vectorToExpr(other)],\n      'euclideanDistance'\n    );\n  }\n\n  /**\n   * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n   * and returns a timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Interpret the 'microseconds' field as microseconds since epoch.\n   * field(\"microseconds\").unixMicrosToTimestamp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n   */\n  unixMicrosToTimestamp(): FunctionExpression {\n    return new FunctionExpression(\n      'unix_micros_to_timestamp',\n      [this],\n      'unixMicrosToTimestamp'\n    );\n  }\n\n  /**\n   * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'timestamp' field to microseconds since epoch.\n   * field(\"timestamp\").timestampToUnixMicros();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.\n   */\n  timestampToUnixMicros(): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_to_unix_micros',\n      [this],\n      'timestampToUnixMicros'\n    );\n  }\n\n  /**\n   * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n   * and returns a timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Interpret the 'milliseconds' field as milliseconds since epoch.\n   * field(\"milliseconds\").unixMillisToTimestamp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n   */\n  unixMillisToTimestamp(): FunctionExpression {\n    return new FunctionExpression(\n      'unix_millis_to_timestamp',\n      [this],\n      'unixMillisToTimestamp'\n    );\n  }\n\n  /**\n   * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'timestamp' field to milliseconds since epoch.\n   * field(\"timestamp\").timestampToUnixMillis();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.\n   */\n  timestampToUnixMillis(): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_to_unix_millis',\n      [this],\n      'timestampToUnixMillis'\n    );\n  }\n\n  /**\n   * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n   * and returns a timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Interpret the 'seconds' field as seconds since epoch.\n   * field(\"seconds\").unixSecondsToTimestamp();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n   */\n  unixSecondsToTimestamp(): FunctionExpression {\n    return new FunctionExpression(\n      'unix_seconds_to_timestamp',\n      [this],\n      'unixSecondsToTimestamp'\n    );\n  }\n\n  /**\n   * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n   *\n   * @example\n   * ```typescript\n   * // Convert the 'timestamp' field to seconds since epoch.\n   * field(\"timestamp\").timestampToUnixSeconds();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.\n   */\n  timestampToUnixSeconds(): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_to_unix_seconds',\n      [this],\n      'timestampToUnixSeconds'\n    );\n  }\n\n  /**\n   * Creates an expression that adds a specified amount of time to this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field.\n   * field(\"timestamp\").timestampAdd(field(\"unit\"), field(\"amount\"));\n   * ```\n   *\n   * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n   * @param amount - The expression evaluates to amount of the unit.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampAdd(unit: Expression, amount: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that adds a specified amount of time to this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Add 1 day to the 'timestamp' field.\n   * field(\"timestamp\").timestampAdd(\"day\", 1);\n   * ```\n   *\n   * @param unit - The unit of time to add (e.g., \"day\", \"hour\").\n   * @param amount - The amount of time to add.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampAdd(unit: TimeUnit, amount: number): FunctionExpression;\n  timestampAdd(\n    unit: Expression | TimeUnit,\n    amount: Expression | number\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_add',\n      [this, valueToDefaultExpr(unit), valueToDefaultExpr(amount)],\n      'timestampAdd'\n    );\n  }\n\n  /**\n   * Creates an expression that subtracts a specified amount of time from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field.\n   * field(\"timestamp\").timestampSubtract(field(\"unit\"), field(\"amount\"));\n   * ```\n   *\n   * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n   * @param amount - The expression evaluates to amount of the unit.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampSubtract(unit: Expression, amount: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that subtracts a specified amount of time from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Subtract 1 day from the 'timestamp' field.\n   * field(\"timestamp\").timestampSubtract(\"day\", 1);\n   * ```\n   *\n   * @param unit - The unit of time to subtract (e.g., \"day\", \"hour\").\n   * @param amount - The amount of time to subtract.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n   */\n  timestampSubtract(unit: TimeUnit, amount: number): FunctionExpression;\n  timestampSubtract(\n    unit: Expression | TimeUnit,\n    amount: Expression | number\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_subtract',\n      [this, valueToDefaultExpr(unit), valueToDefaultExpr(amount)],\n      'timestampSubtract'\n    );\n  }\n\n  /**\n   * Creates an expression that calculates the difference between this timestamp and another timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the difference determined by fields 'startTime' and 'unit'.\n   * field(\"endTime\").timestampDiff(field(\"startTime\"), field(\"unit\"));\n   * ```\n   *\n   * @param start - The expression evaluating to the starting timestamp.\n   * @param unit - The expression evaluates to a unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the difference as an integer.\n   */\n  timestampDiff(start: Expression, unit: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that calculates the difference between this timestamp and another timestamp.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the difference in days between 'endTime' and 'startTime' fields.\n   * field(\"endTime\").timestampDiff(\"startTime\", \"day\");\n   * ```\n   *\n   * @param start - The field name of the starting timestamp.\n   * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the difference as an integer.\n   */\n  timestampDiff(start: string | Expression, unit: TimeUnit): FunctionExpression;\n  timestampDiff(\n    start: string | Expression,\n    unit: TimeUnit | Expression\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'timestamp_diff',\n      [this, fieldOrExpression(start), valueToDefaultExpr(unit)],\n      'timestampDiff'\n    );\n  }\n\n  /**\n   * Creates an expression that extracts a specified part from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Extract the year from the 'createdAt' field.\n   * field('createdAt').timestampExtract('year')\n   * ```\n   *\n   * @param part - The part to extract from the timestamp (e.g., \"year\", \"month\", \"day\").\n   * @param timezone - The timezone to use for extraction. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the extracted part as an integer.\n   */\n  timestampExtract(\n    part: TimePart,\n    timezone?: string | Expression\n  ): FunctionExpression;\n\n  /**\n   * Creates an expression that extracts a specified part from this timestamp expression.\n   *\n   * @example\n   * ```typescript\n   * // Extract the part specified by the field 'extractionPart' from 'createdAt'.\n   * field('createdAt').timestampExtract(field('extractionPart'))\n   * ```\n   *\n   * @param part - The expression evaluating to the part to extract.\n   * @param timezone - The timezone to use for extraction. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the extracted part as an integer.\n   */\n  timestampExtract(\n    part: Expression,\n    timezone?: string | Expression\n  ): FunctionExpression;\n  timestampExtract(\n    part: TimePart | Expression,\n    timezone?: string | Expression\n  ): FunctionExpression {\n    const args = [this, valueToDefaultExpr(part)];\n    if (timezone) {\n      args.push(valueToDefaultExpr(timezone));\n    }\n    return new FunctionExpression(\n      'timestamp_extract',\n      args,\n      'timestampExtract'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that returns the document ID from a path.\n   *\n   * @example\n   * ```typescript\n   * // Get the document ID from a path.\n   * field(\"__path__\").documentId();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.\n   */\n  documentId(): FunctionExpression {\n    return new FunctionExpression('document_id', [this], 'documentId');\n  }\n\n  /**\n   *\n   * Creates an expression that returns the parent document reference of a document reference.\n   *\n   * @example\n   * ```typescript\n   * // Get the parent document reference of a document reference.\n   * field(\"__path__\").parent();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.\n   */\n  parent(): FunctionExpression {\n    return new FunctionExpression('parent', [this], 'parent');\n  }\n\n  /**\n   *\n   * Creates an expression that returns a substring of the results of this expression.\n   *\n   * @param position - Index of the first character of the substring.\n   * @param length - Length of the substring. If not provided, the substring will\n   * end at the end of the input.\n   */\n  substring(position: number, length?: number): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that returns a substring of the results of this expression.\n   *\n   * @param position - An expression returning the index of the first character of the substring.\n   * @param length - An expression returning the length of the substring. If not provided the\n   * substring will end at the end of the input.\n   */\n  substring(position: Expression, length?: Expression): FunctionExpression;\n  substring(\n    position: Expression | number,\n    length?: Expression | number\n  ): FunctionExpression {\n    const positionExpr = valueToDefaultExpr(position);\n    if (length === undefined) {\n      return new FunctionExpression(\n        'substring',\n        [this, positionExpr],\n        'substring'\n      );\n    } else {\n      return new FunctionExpression(\n        'substring',\n        [this, positionExpr, valueToDefaultExpr(length)],\n        'substring'\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that indexes into an array from the beginning or end\n   * and returns the element. If the offset exceeds the array length, an error is\n   * returned. A negative offset, starts from the end.\n   *\n   * @example\n   * ```typescript\n   * // Return the value in the 'tags' field array at index `1`.\n   * field('tags').arrayGet(1);\n   * ```\n   *\n   * @param offset - The index of the element to return.\n   * @returns A new `Expression` representing the 'arrayGet' operation.\n   */\n  arrayGet(offset: number): FunctionExpression;\n\n  /**\n   * Creates an expression that indexes into an array from the beginning or end\n   * and returns the element. If the offset exceeds the array length, an error is\n   * returned. A negative offset, starts from the end.\n   *\n   * @example\n   * ```typescript\n   * // Return the value in the tags field array at index specified by field\n   * // 'favoriteTag'.\n   * field('tags').arrayGet(field('favoriteTag'));\n   * ```\n   *\n   * @param offsetExpr - An `Expression` evaluating to the index of the element to return.\n   * @returns A new `Expression` representing the 'arrayGet' operation.\n   */\n  arrayGet(offsetExpr: Expression): FunctionExpression;\n  arrayGet(offset: Expression | number): FunctionExpression {\n    return new FunctionExpression(\n      'array_get',\n      [this, valueToDefaultExpr(offset)],\n      'arrayGet'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that checks if a given expression produces an error.\n   *\n   * @example\n   * ```typescript\n   * // Check if the result of a calculation is an error\n   * field(\"title\").arrayContains(1).isError();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isError' check.\n   */\n  isError(): BooleanExpression {\n    return new FunctionExpression('is_error', [this], 'isError').asBoolean();\n  }\n\n  /**\n   *\n   * Creates an expression that returns the result of the `catchExpr` argument\n   * if there is an error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Returns the first item in the title field arrays, or returns\n   * // the entire title field if the array is empty or the field is another type.\n   * field(\"title\").arrayGet(0).ifError(field(\"title\"));\n   * ```\n   *\n   * @param catchExpr - The catch expression that will be evaluated and\n   * returned if this expression produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchExpr: Expression): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Returns the first item in the title field arrays, or returns\n   * // \"Default Title\"\n   * field(\"title\").arrayGet(0).ifError(\"Default Title\");\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: unknown): FunctionExpression;\n  ifError(catchValue: unknown): FunctionExpression | BooleanExpression {\n    const result = new FunctionExpression(\n      'if_error',\n      [this, valueToDefaultExpr(catchValue)],\n      'ifError'\n    );\n\n    return catchValue instanceof BooleanExpression\n      ? result.asBoolean()\n      : result;\n  }\n\n  /**\n   *\n   * Creates an expression that returns `true` if the result of this expression\n   * is absent. Otherwise, returns `false` even if the value is `null`.\n   *\n   * @example\n   * ```typescript\n   * // Check if the field `value` is absent.\n   * field(\"value\").isAbsent();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isAbsent' check.\n   */\n  isAbsent(): BooleanExpression {\n    return new FunctionExpression('is_absent', [this], 'isAbsent').asBoolean();\n  }\n\n  /**\n   *\n   * Creates an expression that removes a key from the map produced by evaluating this expression.\n   *\n   * @example\n   * ```\n   * // Removes the key 'baz' from the input map.\n   * map({foo: 'bar', baz: true}).mapRemove('baz');\n   * ```\n   *\n   * @param key - The name of the key to remove from the input map.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapRemove' operation.\n   */\n  mapRemove(key: string): FunctionExpression;\n  /**\n   *\n   * Creates an expression that removes a key from the map produced by evaluating this expression.\n   *\n   * @example\n   * ```\n   * // Removes the key 'baz' from the input map.\n   * map({foo: 'bar', baz: true}).mapRemove(constant('baz'));\n   * @example\n   * ```\n   *\n   * @param keyExpr - An expression that produces the name of the key to remove from the input map.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapRemove' operation.\n   */\n  mapRemove(keyExpr: Expression): FunctionExpression;\n  mapRemove(stringExpr: Expression | string): FunctionExpression {\n    return new FunctionExpression(\n      'map_remove',\n      [this, valueToDefaultExpr(stringExpr)],\n      'mapRemove'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that merges multiple map values.\n   *\n   * @example\n   * ```\n   * // Merges the map in the settings field with, a map literal, and a map in\n   * // that is conditionally returned by another expression\n   * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {})\n   * ```\n   *\n   * @param secondMap - A required second map to merge. Represented as a literal or\n   * an expression that returns a map.\n   * @param otherMaps - Optional additional maps to merge. Each map is represented\n   * as a literal or an expression that returns a map.\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapMerge' operation.\n   */\n  mapMerge(\n    secondMap: Record<string, unknown> | Expression,\n    ...otherMaps: Array<Record<string, unknown> | Expression>\n  ): FunctionExpression {\n    const secondMapExpr = valueToDefaultExpr(secondMap);\n    const otherMapExprs = otherMaps.map(valueToDefaultExpr);\n    return new FunctionExpression(\n      'map_merge',\n      [this, secondMapExpr, ...otherMapExprs],\n      'mapMerge'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the value of this expression raised to the power of another expression.\n   *\n   * @example\n   * ```typescript\n   * // Raise the value of the 'base' field to the power of the 'exponent' field.\n   * field(\"base\").pow(field(\"exponent\"));\n   * ```\n   *\n   * @param exponent - The expression to raise this expression to the power of.\n   * @returns A new `Expression` representing the power operation.\n   */\n  pow(exponent: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that returns the value of this expression raised to the power of a constant value.\n   *\n   * @example\n   * ```typescript\n   * // Raise the value of the 'base' field to the power of 2.\n   * field(\"base\").pow(2);\n   * ```\n   *\n   * @param exponent - The constant value to raise this expression to the power of.\n   * @returns A new `Expression` representing the power operation.\n   */\n  pow(exponent: number): FunctionExpression;\n  pow(exponent: number | Expression): FunctionExpression {\n    return new FunctionExpression('pow', [this, valueToDefaultExpr(exponent)]);\n  }\n\n  /**\n   * Creates an expression that truncates the numeric value to an integer.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the 'rating' field\n   * field(\"rating\").trunc();\n   * ```\n   *\n   * @returns A new `Expression` representing the truncated value.\n   */\n  trunc(): FunctionExpression;\n\n  /**\n   * Creates an expression that truncates a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the value of the 'rating' field to two decimal places.\n   * field(\"rating\").trunc(2);\n   * ```\n   *\n   * @param decimalPlaces - A constant specifying the truncation precision in decimal places.\n   * @returns A new `Expression` representing the truncated value.\n   */\n  trunc(decimalPlaces: number): FunctionExpression;\n\n  /**\n   * Creates an expression that truncates a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the value of the 'rating' field to two decimal places.\n   * field(\"rating\").trunc(constant(2));\n   * ```\n   *\n   * @param decimalPlaces - An expression specifying the truncation precision in decimal places.\n   * @returns A new `Expression` representing the truncated value.\n   */\n  trunc(decimalPlaces: Expression): FunctionExpression;\n  trunc(decimalPlaces?: number | Expression): FunctionExpression {\n    if (decimalPlaces === undefined) {\n      return new FunctionExpression('trunc', [this]);\n    } else {\n      return new FunctionExpression(\n        'trunc',\n        [this, valueToDefaultExpr(decimalPlaces)],\n        'trunc'\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that rounds a numeric value to the nearest whole number.\n   *\n   * @example\n   * ```typescript\n   * // Round the value of the 'price' field.\n   * field(\"price\").round();\n   * ```\n   *\n   * @returns A new `Expression` representing the rounded value.\n   */\n  round(): FunctionExpression;\n  /**\n   * Creates an expression that rounds a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Round the value of the 'price' field to two decimal places.\n   * field(\"price\").round(2);\n   * ```\n   *\n   * @param decimalPlaces - A constant specifying the rounding precision in decimal places.\n   *\n   * @returns A new `Expression` representing the rounded value.\n   */\n  round(decimalPlaces: number): FunctionExpression;\n  /**\n   * Creates an expression that rounds a numeric value to the specified number of decimal places.\n   *\n   * @example\n   * ```typescript\n   * // Round the value of the 'price' field to two decimal places.\n   * field(\"price\").round(constant(2));\n   * ```\n   *\n   * @param decimalPlaces - An expression specifying the rounding precision in decimal places.\n   *\n   * @returns A new `Expression` representing the rounded value.\n   */\n  round(decimalPlaces: Expression): FunctionExpression;\n  round(decimalPlaces?: number | Expression): FunctionExpression {\n    if (decimalPlaces === undefined) {\n      return new FunctionExpression('round', [this]);\n    } else {\n      return new FunctionExpression(\n        'round',\n        [this, valueToDefaultExpr(decimalPlaces)],\n        'round'\n      );\n    }\n  }\n\n  /**\n   * Creates an expression that returns the collection ID from a path.\n   *\n   * @example\n   * ```typescript\n   * // Get the collection ID from a path.\n   * field(\"__path__\").collectionId();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.\n   */\n  collectionId(): FunctionExpression {\n    return new FunctionExpression('collection_id', [this]);\n  }\n\n  /**\n   * Creates an expression that calculates the length of a string, array, map, vector, or bytes.\n   *\n   * @example\n   * ```typescript\n   * // Get the length of the 'name' field.\n   * field(\"name\").length();\n   *\n   * // Get the number of items in the 'cart' array.\n   * field(\"cart\").length();\n   * ```\n   *\n   * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.\n   */\n  length(): FunctionExpression {\n    return new FunctionExpression('length', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the natural logarithm of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the natural logarithm of the 'value' field.\n   * field(\"value\").ln();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the natural logarithm of the numeric value.\n   */\n  ln(): FunctionExpression {\n    return new FunctionExpression('ln', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the square root of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the square root of the 'value' field.\n   * field(\"value\").sqrt();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.\n   */\n  sqrt(): FunctionExpression {\n    return new FunctionExpression('sqrt', [this]);\n  }\n\n  /**\n   * Creates an expression that reverses a string.\n   *\n   * @example\n   * ```typescript\n   * // Reverse the value of the 'myString' field.\n   * field(\"myString\").stringReverse();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n   */\n  stringReverse(): FunctionExpression {\n    return new FunctionExpression('string_reverse', [this]);\n  }\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else\n   * return the result of this expression evaluation.\n   *\n   * @example\n   * ```typescript\n   * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n   * // if the field is absent.\n   * field(\"optional_field\").ifAbsent(\"default_value\")\n   * ```\n   *\n   * @param elseValue - The value that will be returned if this Expression evaluates to an absent value.\n   * @returns A new [Expression] representing the ifAbsent operation.\n   */\n  ifAbsent(elseValue: unknown): Expression;\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else\n   * return the result of this expression evaluation.\n   *\n   * @example\n   * ```typescript\n   * // Returns the value of the optional field 'optional_field', or if that is\n   * // absent, then returns the value of the field `default_field`.\n   * field(\"optional_field\").ifAbsent(field('default_field'))\n   * ```\n   *\n   * @param elseExpression - The Expression that will be evaluated if this Expression evaluates to an absent value.\n   * @returns A new [Expression] representing the ifAbsent operation.\n   */\n  ifAbsent(elseExpression: unknown): Expression;\n\n  ifAbsent(elseValueOrExpression: Expression | unknown): Expression {\n    return new FunctionExpression(\n      'if_absent',\n      [this, valueToDefaultExpr(elseValueOrExpression)],\n      'ifAbsent'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression evaluates to null, else\n   * return the result of this expression evaluation.\n   *\n   * @remarks\n   * This function provides a fallback for both absent and explicit null values. In contrast,\n   * `ifAbsent()` only triggers for missing fields.\n   *\n   * @example\n   * ```typescript\n   * // Returns the user's preferred name, or if that is null, returns their full name.\n   * field(\"preferredName\").ifNull(field(\"fullName\"))\n   * ```\n   *\n   * @param elseExpression - The Expression that will be evaluated if this Expression evaluates to null.\n   * @returns A new `Expression` representing the ifNull operation.\n   */\n  ifNull(elseExpression: Expression): FunctionExpression;\n\n  /**\n   * Creates an expression that returns the `elseValue` argument if this expression evaluates to null, else\n   * return the result of this expression evaluation.\n   *\n   * @remarks\n   * This function provides a fallback for both absent and explicit null values. In contrast,\n   * `ifAbsent()` only triggers for missing fields.\n   *\n   * @example\n   * ```typescript\n   * // Returns the user's display name, or returns \"Anonymous\" if the field is null.\n   * field(\"displayName\").ifNull(\"Anonymous\")\n   * ```\n   *\n   * @param elseValue - The value that will be returned if this Expression evaluates to null.\n   * @returns A new `Expression` representing the ifNull operation.\n   */\n  ifNull(elseValue: unknown): FunctionExpression;\n  ifNull(elseValueOrExpression: Expression | unknown): FunctionExpression {\n    return new FunctionExpression(\n      'if_null',\n      [this, valueToDefaultExpr(elseValueOrExpression)],\n      'ifNull'\n    );\n  }\n\n  /**\n   * Creates an expression that returns the first non-null, non-absent argument, without evaluating\n   * the rest of the arguments. When all arguments are null or absent, returns the last argument.\n   *\n   * @example\n   * ```typescript\n   * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',\n   * // or the last argument if all previous fields are null.\n   * field(\"preferredName\").coalesce(field(\"fullName\"), \"Anonymous\");\n   * ```\n   *\n   * @param replacement - The value to use if this expression evaluates to null.\n   * @param others - Optional additional values to check if previous values are null.\n   * @returns A new `Expression` representing the coalesce operation.\n   */\n  coalesce(\n    replacement: Expression | unknown,\n    ...others: Array<Expression | unknown>\n  ): FunctionExpression {\n    return new FunctionExpression(\n      'coalesce',\n      [\n        this,\n        valueToDefaultExpr(replacement),\n        ...others.map(valueToDefaultExpr)\n      ],\n      'coalesce'\n    );\n  }\n\n  /**\n   * Creates an expression that joins the elements of an array into a string.\n   *\n   * @example\n   * ```typescript\n   * // Join the elements of the 'tags' field with the delimiter from the 'separator' field.\n   * field(\"tags\").join(field(\"separator\"))\n   * ```\n   *\n   * @param delimiterExpression - The expression that evaluates to the delimiter string.\n   * @returns A new Expression representing the join operation.\n   */\n  join(delimiterExpression: Expression): Expression;\n\n  /**\n   * Creates an expression that joins the elements of an array field into a string.\n   *\n   * @example\n   * ```typescript\n   * // Join the elements of the 'tags' field with a comma and space.\n   * field(\"tags\").join(\", \")\n   * ```\n   *\n   * @param delimiter - The string to use as a delimiter.\n   * @returns A new Expression representing the join operation.\n   */\n  join(delimiter: string): Expression;\n\n  join(delimeterValueOrExpression: string | Expression): Expression {\n    return new FunctionExpression(\n      'join',\n      [this, valueToDefaultExpr(delimeterValueOrExpression)],\n      'join'\n    );\n  }\n\n  /**\n   * Creates an expression that computes the base-10 logarithm of a numeric value.\n   *\n   * @example\n   * ```typescript\n   * // Compute the base-10 logarithm of the 'value' field.\n   * field(\"value\").log10();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the base-10 logarithm of the numeric value.\n   */\n  log10(): FunctionExpression {\n    return new FunctionExpression('log10', [this]);\n  }\n\n  /**\n   * Creates an expression that computes the sum of the elements in an array.\n   *\n   * @example\n   * ```typescript\n   * // Compute the sum of the elements in the 'scores' field.\n   * field(\"scores\").arraySum();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sum of the elements in the array.\n   */\n  arraySum(): FunctionExpression {\n    return new FunctionExpression('sum', [this]);\n  }\n\n  /**\n   * Creates an expression that splits the result of this expression into an\n   * array of substrings based on the provided delimiter.\n   *\n   * @example\n   * ```typescript\n   * // Split the 'scoresCsv' field on delimiter ','\n   * field('scoresCsv').split(',')\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n   */\n  split(delimiter: string): FunctionExpression;\n\n  /**\n   * Creates an expression that splits the result of this expression into an\n   * array of substrings based on the provided delimiter.\n   *\n   * @example\n   * ```typescript\n   * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format\n   * field('scores').split(conditional(field('format').equal('csv'), constant(','), constant(':')))\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n   */\n  split(delimiter: Expression): FunctionExpression;\n  split(delimiter: string | Expression): FunctionExpression {\n    return new FunctionExpression('split', [\n      this,\n      valueToDefaultExpr(delimiter)\n    ]);\n  }\n\n  /**\n   * Creates an expression that truncates a timestamp to a specified granularity.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the 'createdAt' timestamp to the beginning of the day.\n   * field('createdAt').timestampTruncate('day')\n   * ```\n   *\n   * @param granularity - The granularity to truncate to.\n   * @param timezone - The timezone to use for truncation. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the truncated timestamp.\n   */\n  timestampTruncate(\n    granularity: TimeGranularity,\n    timezone?: string | Expression\n  ): FunctionExpression;\n\n  /**\n   * Creates an expression that truncates a timestamp to a specified granularity.\n   *\n   * @example\n   * ```typescript\n   * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.\n   * field('createdAt').timestampTruncate(field('granularity'))\n   * ```\n   *\n   * @param granularity - The granularity to truncate to.\n   * @param timezone - The timezone to use for truncation. Valid values are from\n   * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the truncated timestamp.\n   */\n  timestampTruncate(\n    granularity: Expression,\n    timezone?: string | Expression\n  ): FunctionExpression;\n  timestampTruncate(\n    granularity: TimeGranularity | Expression,\n    timezone?: string | Expression\n  ): FunctionExpression {\n    const args = [this, valueToDefaultExpr(granularity)];\n    if (timezone) {\n      args.push(valueToDefaultExpr(timezone));\n    }\n    return new FunctionExpression('timestamp_trunc', args);\n  }\n\n  // TODO(search) enable with backend support\n  // /**\n  //  * Evaluates if the result of this `expression` is between\n  //  * the `lowerBound` (inclusive) and `upperBound` (inclusive).\n  //  *\n  //  * @example\n  //  * ```\n  //  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n  //  * field('tireWidth').between(constant(2.2), constant(2.4))\n  //  *\n  //  * // This is functionally equivalent to\n  //  * and(field('tireWidth').greaterThanOrEqual(contant(2.2)), field('tireWidth').lessThanOrEqual(constant(2.4)))\n  //  * ```\n  //  *\n  //  * @param lowerBound - Lower bound (inclusive) of the range.\n  //  * @param upperBound - Upper bound (inclusive) of the range.\n  //  */\n  // between(lowerBound: Expression, upperBound: Expression): BooleanExpression;\n  //\n  // /**\n  //  * Evaluates if the result of this `expression` is between\n  //  * the `lowerBound` (inclusive) and `upperBound` (inclusive).\n  //  *\n  //  * @example\n  //  * ```\n  //  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n  //  * field('tireWidth').between(2.2, 2.4)\n  //  *\n  //  * // This is functionally equivalent to\n  //  * and(field('tireWidth').greaterThanOrEqual(2.2), field('tireWidth').lessThanOrEqual(2.4))\n  //  * ```\n  //  *\n  //  * @param lowerBound - Lower bound (inclusive) of the range.\n  //  * @param upperBound - Upper bound (inclusive) of the range.\n  //  */\n  // between(lowerBound: unknown, upperBound: unknown): BooleanExpression;\n  //\n  // between(lowerBound: unknown, upperBound: unknown): BooleanExpression {\n  //   return new FunctionExpression('between', [\n  //     this,\n  //     valueToDefaultExpr(lowerBound),\n  //     valueToDefaultExpr(upperBound)\n  //   ]).asBoolean();\n  // }\n\n  // TODO(search) enable with backend support\n  // /**\n  //  * Evaluates to an HTML-formatted text snippet that renders terms matching\n  //  * the search query in `<b>bold</b>`.\n  //  *\n  //  * @remarks This Expression can only be used within a `search` stage.\n  //  *\n  //  * @param rquery Define the search query using the search domain-specific language (DSL).\n  //  */\n  // snippet(rquery: string): Expression;\n  //\n  // /**\n  //  * Evaluates to an HTML-formatted text snippet that renders terms matching\n  //  * the search query in `<b>bold</b>`.\n  //  *\n  //  * @remarks This Expression can only be used within a `search` stage.\n  //  *\n  //  * @param options Define how snippeting behaves.\n  //  */\n  // snippet(options: SnippetOptions): Expression;\n  //\n  // snippet(queryOrOptions: string | SnippetOptions): Expression {\n  //   const options: SnippetOptions = isString(queryOrOptions)\n  //     ? { rquery: queryOrOptions }\n  //     : queryOrOptions;\n  //   const rquery = options.rquery;\n  //   const internalOptions = {\n  //     maxSnippetWidth: options.maxSnippetWidth,\n  //     maxSnippets: options.maxSnippets,\n  //     separator: options.separator\n  //   };\n  //   return new SnippetExpression([this, constant(rquery)], internalOptions);\n  // }\n\n  // TODO(new-expression): Add new expression method definitions above this line\n\n  /**\n   * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on this expression.\n   *\n   * @example\n   * ```typescript\n   * // Sort documents by the 'name' field in ascending order\n   * firestore.pipeline().collection(\"users\")\n   *   .sort(field(\"name\").ascending());\n   * ```\n   *\n   * @returns A new `Ordering` for ascending sorting.\n   */\n  ascending(): Ordering {\n    return ascending(this);\n  }\n\n  /**\n   * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on this expression.\n   *\n   * @example\n   * ```typescript\n   * // Sort documents by the 'createdAt' field in descending order\n   * firestore.pipeline().collection(\"users\")\n   *   .sort(field(\"createdAt\").descending());\n   * ```\n   *\n   * @returns A new `Ordering` for descending sorting.\n   */\n  descending(): Ordering {\n    return descending(this);\n  }\n\n  /**\n   * Assigns an alias to this expression.\n   *\n   * Aliases are useful for renaming fields in the output of a stage or for giving meaningful\n   * names to calculated values.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the total price and assign it the alias \"totalPrice\" and add it to the output.\n   * firestore.pipeline().collection(\"items\")\n   *   .addFields(field(\"price\").multiply(field(\"quantity\")).as(\"totalPrice\"));\n   * ```\n   *\n   * @param name - The alias to assign to this expression.\n   * @returns A new {@link @firebase/firestore/pipelines#AliasedExpression} that wraps this\n   *     expression and associates it with the provided alias.\n   */\n  as(name: string): AliasedExpression {\n    return new AliasedExpression(this, name, 'as');\n  }\n}\n\n/**\n * Specify time units for expressions.\n */\nexport type TimeUnit =\n  | 'microsecond'\n  | 'millisecond'\n  | 'second'\n  | 'minute'\n  | 'hour'\n  | 'day';\n\n/**\n * Specify time granularity for expressions.\n */\nexport type TimeGranularity =\n  | TimeUnit\n  | 'week'\n  | 'week(monday)'\n  | 'week(tuesday)'\n  | 'week(wednesday)'\n  | 'week(thursday)'\n  | 'week(friday)'\n  | 'week(saturday)'\n  | 'week(sunday)'\n  | 'isoweek'\n  | 'month'\n  | 'quarter'\n  | 'year'\n  | 'isoyear';\n\n/**\n * Specify time parts for `timestampExtract` expressions.\n */\nexport type TimePart = TimeGranularity | 'dayofweek' | 'dayofyear';\n\n/**\n *\n * An interface that represents a selectable expression.\n */\nexport interface Selectable {\n  selectable: true;\n  /**\n   * @private\n   * @internal\n   */\n  readonly alias: string;\n  /**\n   * @private\n   * @internal\n   */\n  readonly expr: Expression;\n}\n\n/**\n *\n * A class that represents an aggregate function.\n */\nexport class AggregateFunction implements ProtoValueSerializable, UserData {\n  exprType: ExpressionType = 'AggregateFunction';\n\n  /**\n   * @internal\n   */\n  _methodName?: string;\n\n  constructor(private name: string, private params: Expression[]) {}\n\n  /**\n   * @internal\n   * @private\n   */\n  static _create(\n    name: string,\n    params: Expression[],\n    methodName: string\n  ): AggregateFunction {\n    const af = new AggregateFunction(name, params);\n    af._methodName = methodName;\n\n    return af;\n  }\n\n  /**\n   * Assigns an alias to this AggregateFunction. The alias specifies the name that\n   * the aggregated value will have in the output document.\n   *\n   * @example\n   * ```typescript\n   * // Calculate the average price of all items and assign it the alias \"averagePrice\".\n   * firestore.pipeline().collection(\"items\")\n   *   .aggregate(field(\"price\").average().as(\"averagePrice\"));\n   * ```\n   *\n   * @param name - The alias to assign to this AggregateFunction.\n   * @returns A new {@link @firebase/firestore/pipelines#AliasedAggregate} that wraps this\n   *     AggregateFunction and associates it with the provided alias.\n   */\n  as(name: string): AliasedAggregate {\n    return new AliasedAggregate(this, name, 'as');\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      functionValue: {\n        name: this.name,\n        args: this.params.map(p => p._toProto(serializer))\n      }\n    };\n  }\n\n  _protoValueType = 'ProtoValue' as const;\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    this.params.forEach(expr => {\n      return expr._readUserData(context);\n    });\n  }\n}\n\n/**\n *\n * An AggregateFunction with alias.\n */\nexport class AliasedAggregate implements UserData {\n  constructor(\n    readonly aggregate: AggregateFunction,\n    readonly alias: string,\n    readonly _methodName: string | undefined\n  ) {}\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.aggregate._readUserData(context);\n  }\n}\n\nexport class AliasedExpression implements Selectable, UserData {\n  exprType: ExpressionType = 'AliasedExpression';\n  selectable = true as const;\n\n  constructor(\n    readonly expr: Expression,\n    readonly alias: string,\n    readonly _methodName: string | undefined\n  ) {}\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.expr._readUserData(context);\n  }\n}\n\n/**\n * @internal\n */\nclass ListOfExprs extends Expression implements UserData {\n  expressionType: ExpressionType = 'ListOfExpressions';\n\n  constructor(\n    private exprs: Expression[],\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      arrayValue: {\n        values: this.exprs.map(p => p._toProto(serializer)!)\n      }\n    };\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.exprs.forEach((expr: Expression) => expr._readUserData(context));\n  }\n}\n\n/**\n *\n * Represents a reference to a field in a Firestore document, or outputs of a {@link @firebase/firestore/pipelines#Pipeline} stage.\n *\n * <p>Field references are used to access document field values in expressions and to specify fields\n * for sorting, filtering, and projecting data in Firestore pipelines.\n *\n * <p>You can create a `Field` instance using the static {@link @firebase/firestore/pipelines#field} method:\n *\n * @example\n * ```typescript\n * // Create a Field instance for the 'name' field\n * const nameField = field(\"name\");\n *\n * // Create a Field instance for a nested field 'address.city'\n * const cityField = field(\"address.city\");\n * ```\n */\nexport class Field extends Expression implements Selectable {\n  readonly expressionType: ExpressionType = 'Field';\n  selectable = true as const;\n\n  /**\n   * @internal\n   * @private\n   * @hideconstructor\n   * @param fieldPath\n   */\n  constructor(\n    private fieldPath: InternalFieldPath,\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  get fieldName(): string {\n    return this.fieldPath.canonicalString();\n  }\n\n  get alias(): string {\n    return this.fieldName;\n  }\n\n  get expr(): Expression {\n    return this;\n  }\n\n  // TODO(search) enable with backend support\n  // /**\n  //  * Perform a full-text search on this field.\n  //  *\n  //  * @remarks This Expression can only be used within a `search` stage.\n  //  *\n  //  * @param rquery Define the search query using the search domain-specific language (DSL).\n  //  */\n  // matches(rquery: string | Expression): BooleanExpression {\n  //   return new FunctionExpression(\n  //     'matches',\n  //     [this, valueToDefaultExpr(rquery)],\n  //     'matches'\n  //   ).asBoolean();\n  // }\n\n  /**\n   * @beta\n   * Evaluates to the distance in meters between the location specified\n   * by this field and the query location.\n   *\n   * @remarks This Expression can only be used within a `search` stage.\n   *\n   * @param location - Compute distance to this GeoPoint.\n   */\n  geoDistance(location: GeoPoint | Expression): Expression {\n    return new FunctionExpression(\n      'geo_distance',\n      [this, valueToDefaultExpr(location)],\n      'geoDistance'\n    );\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      fieldReferenceValue: this.fieldPath.canonicalString()\n    };\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {}\n}\n\n/**\n * Creates a {@link @firebase/firestore/pipelines#Field} instance representing the field at the given path.\n *\n * The path can be a simple field name (e.g., \"name\") or a dot-separated path to a nested field\n * (e.g., \"address.city\").\n *\n * @example\n * ```typescript\n * // Create a Field instance for the 'title' field\n * const titleField = field(\"title\");\n *\n * // Create a Field instance for a nested field 'author.firstName'\n * const authorFirstNameField = field(\"author.firstName\");\n * ```\n *\n * @param name - The path to the field.\n * @returns A new {@link @firebase/firestore/pipelines#Field} instance representing the specified field.\n */\nexport function field(name: string): Field;\n\n/**\n * Creates a {@link @firebase/firestore/pipelines#Field} instance representing the field at the given path.\n *\n * @param path - A FieldPath specifying the field.\n * @returns A new {@link @firebase/firestore/pipelines#Field} instance representing the specified field.\n */\nexport function field(path: FieldPath): Field;\nexport function field(nameOrPath: string | FieldPath): Field {\n  return _field(nameOrPath, 'field');\n}\n\nexport function _field(\n  nameOrPath: string | FieldPath,\n  methodName: string | undefined\n): Field {\n  if (typeof nameOrPath === 'string') {\n    if (DOCUMENT_KEY_NAME === nameOrPath) {\n      return new Field(documentIdFieldPath()._internalPath, methodName);\n    }\n    return new Field(fieldPathFromArgument('field', nameOrPath), methodName);\n  } else {\n    return new Field(nameOrPath._internalPath, methodName);\n  }\n}\n\n/**\n * @internal\n *\n * Represents a constant value that can be used in a Firestore pipeline expression.\n *\n * You can create a `Constant` instance using the static {@link @firebase/firestore/pipelines#field} method:\n *\n * @example\n * ```typescript\n * // Create a Constant instance for the number 10\n * const ten = constant(10);\n *\n * // Create a Constant instance for the string \"hello\"\n * const hello = constant(\"hello\");\n * ```\n */\nexport class Constant extends Expression {\n  readonly expressionType: ExpressionType = 'Constant';\n\n  private _protoValue?: ProtoValue;\n\n  /**\n   * @private\n   * @internal\n   * @hideconstructor\n   * @param value - The value of the constant.\n   */\n  constructor(\n    private value: unknown,\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  static _fromProto(value: ProtoValue): Constant {\n    const result = new Constant(value, undefined);\n    result._protoValue = value;\n    return result;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(_: JsonProtoSerializer): ProtoValue {\n    hardAssert(\n      this._protoValue !== undefined,\n      0x00ed,\n      'Value of this constant has not been serialized to proto value'\n    );\n    return this._protoValue;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    if (isFirestoreValue(this._protoValue)) {\n      return;\n    } else {\n      this._protoValue = parseData(this.value, context)!;\n    }\n  }\n}\n\n/**\n * Creates a `Constant` instance for a number value.\n *\n * @param value - The number value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: number): Expression;\n\n/**\n * Creates a `Constant` instance for a string value.\n *\n * @param value - The string value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: string): Expression;\n\n/**\n * Creates a `BooleanExpression` instance for a boolean value.\n *\n * @param value - The boolean value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: boolean): BooleanExpression;\n\n/**\n * Creates a `Constant` instance for a null value.\n *\n * @param value - The null value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: null): Expression;\n\n/**\n * Creates a `Constant` instance for a GeoPoint value.\n *\n * @param value - The GeoPoint value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: GeoPoint): Expression;\n\n/**\n * Creates a `Constant` instance for a Timestamp value.\n *\n * @param value - The Timestamp value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: Timestamp): Expression;\n\n/**\n * Creates a `Constant` instance for a Date value.\n *\n * @param value - The Date value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: Date): Expression;\n\n/**\n * Creates a `Constant` instance for a Bytes value.\n *\n * @param value - The Bytes value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: Bytes): Expression;\n\n/**\n * Creates a `Constant` instance for a DocumentReference value.\n *\n * @param value - The DocumentReference value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: DocumentReference): Expression;\n\n/**\n * Creates a `Constant` instance for a Firestore proto value.\n * For internal use only.\n * @private\n * @internal\n * @param value - The Firestore proto value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: ProtoValue): Expression;\n\n/**\n * Creates a `Constant` instance for a VectorValue value.\n *\n * @param value - The VectorValue value.\n * @returns A new `Constant` instance.\n */\nexport function constant(value: VectorValue): Expression;\n\nexport function constant(value: unknown): Expression | BooleanExpression {\n  return _constant(value, 'constant');\n}\n\n/**\n * @internal\n * @private\n * @param value\n * @param methodName\n */\nexport function _constant(\n  value: unknown,\n  methodName: string | undefined\n): Constant | BooleanExpression {\n  const c = new Constant(value, methodName);\n  if (typeof value === 'boolean') {\n    return new BooleanConstant(c);\n  } else {\n    return c;\n  }\n}\n\n/**\n * Internal only\n * @internal\n * @private\n */\nexport class MapValue extends Expression {\n  constructor(\n    private plainObject: Map<string, Expression>,\n    readonly _methodName: string | undefined\n  ) {\n    super();\n  }\n\n  expressionType: ExpressionType = 'Constant';\n\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    this.plainObject.forEach(expr => {\n      expr._readUserData(context);\n    });\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return toMapValue(serializer, this.plainObject);\n  }\n}\n\n/**\n *\n * This class defines the base class for Firestore {@link @firebase/firestore/pipelines#Pipeline} functions, which can be evaluated within pipeline\n * execution.\n *\n * Typically, you would not use this class or its children directly. Use either the functions like {@link @firebase/firestore/pipelines#and}, {@link @firebase/firestore/pipelines#(equal:1)},\n * or the methods on {@link @firebase/firestore/pipelines#Expression} ({@link @firebase/firestore/pipelines#Expression.(equal:1)}, {@link @firebase/firestore/pipelines#Expression.(lessThan:1)}, etc.) to construct new Function instances.\n */\nexport class FunctionExpression extends Expression {\n  readonly expressionType: ExpressionType = 'Function';\n\n  constructor(name: string, params: Expression[]);\n\n  /**\n   * @hideconstructor\n   */\n  constructor(\n    name: string,\n    params: Expression[],\n    _methodName?: string,\n    options?: {}\n  );\n\n  /**\n   * @hideconstructor\n   */\n  constructor(\n    private name: string,\n    private params: Expression[],\n    methodName?: string,\n    options?: {}\n  ) {\n    super();\n\n    if (methodName !== undefined) {\n      this._methodName = methodName;\n    }\n    if (options !== undefined) {\n      this._options = options;\n    }\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _methodName: string | undefined;\n\n  /**\n   * @private\n   * @internal\n   */\n  private _options: {} | undefined;\n\n  /**\n   * @private\n   * @internal\n   */\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _optionsProto:\n    | ApiClientObjectMap<firestoreV1ApiClientInterfaces.Value>\n    | undefined = undefined;\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    const returnValue: ProtoValue = {\n      functionValue: {\n        name: this.name,\n        args: this.params.map(p => p._toProto(serializer))\n      }\n    };\n\n    if (this._optionsProto) {\n      returnValue.functionValue!.options = this._optionsProto;\n    }\n\n    return returnValue;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    context = this._methodName\n      ? context.contextWith({ methodName: this._methodName })\n      : context;\n    this.params.forEach(expr => {\n      return expr._readUserData(context);\n    });\n    if (this._options) {\n      this._optionsProto = this._optionsUtil.getOptionsProto(\n        context,\n        this._options\n      );\n    }\n  }\n}\n\n/**\n *\n * An interface that represents a filter condition.\n */\nexport abstract class BooleanExpression extends Expression {\n  abstract get _expr(): Expression;\n\n  get _methodName(): string | undefined {\n    return this._expr._methodName;\n  }\n\n  /**\n   * Creates an aggregation that finds the count of input documents satisfying\n   * this boolean expression.\n   *\n   * @example\n   * ```typescript\n   * // Find the count of documents with a score greater than 90\n   * field(\"score\").greaterThan(90).countIf().as(\"highestScore\");\n   * ```\n   *\n   * @returns A new `AggregateFunction` representing the 'countIf' aggregation.\n   */\n  countIf(): AggregateFunction {\n    return AggregateFunction._create('count_if', [this], 'countIf');\n  }\n\n  /**\n   * Creates an expression that negates this boolean expression.\n   *\n   * @example\n   * ```typescript\n   * // Find documents where the 'tags' field does not contain 'completed'\n   * field(\"tags\").arrayContains(\"completed\").not();\n   * ```\n   *\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.\n   */\n  not(): BooleanExpression {\n    return new FunctionExpression('not', [this], 'not').asBoolean();\n  }\n\n  /**\n   * Creates a conditional expression that evaluates to the 'then' expression\n   * if `this` expression evaluates to `true`,\n   * or evaluates to the 'else' expression if `this` expressions evaluates `false`.\n   *\n   * @example\n   * ```typescript\n   * // If 'age' is greater than 18, return \"Adult\"; otherwise, return \"Minor\".\n   * field(\"age\").greaterThanOrEqual(18).conditional(constant(\"Adult\"), constant(\"Minor\"));\n   * ```\n   *\n   * @param thenExpr - The expression to evaluate if the condition is true.\n   * @param elseExpr - The expression to evaluate if the condition is false.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.\n   */\n  conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression {\n    return new FunctionExpression(\n      'conditional',\n      [this, thenExpr, elseExpr],\n      'conditional'\n    );\n  }\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error\n   * // but always returns a boolean expression.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(constant(false));\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: BooleanExpression): BooleanExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error\n   * // but always returns a boolean expression.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(false);\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: boolean): BooleanExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(constant(0));\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: Expression): FunctionExpression;\n\n  /**\n   *\n   * Creates an expression that returns the `catch` argument if there is an\n   * error, else return the result of this expression.\n   *\n   * @example\n   * ```typescript\n   * // Create an expression that protects against a divide by zero error.\n   * constant(50).divide(field('length')).greaterThan(1).ifError(0);\n   * ```\n   *\n   * @param catchValue - The value that will be returned if this expression\n   * produces an error.\n   * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n   */\n  ifError(catchValue: unknown): FunctionExpression;\n  ifError(catchValue: unknown): unknown {\n    const normalizedCatchValue = valueToDefaultExpr(catchValue);\n    const expr = new FunctionExpression(\n      'if_error',\n      [this, normalizedCatchValue],\n      'ifError'\n    );\n\n    return normalizedCatchValue instanceof BooleanExpression\n      ? expr.asBoolean()\n      : expr;\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return this._expr._toProto(serializer);\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this._expr._readUserData(context);\n  }\n}\n\nexport class BooleanFunctionExpression extends BooleanExpression {\n  readonly expressionType: ExpressionType = 'Function';\n  constructor(readonly _expr: FunctionExpression) {\n    super();\n  }\n}\n\nexport class BooleanConstant extends BooleanExpression {\n  readonly expressionType: ExpressionType = 'Constant';\n  constructor(readonly _expr: Constant) {\n    super();\n  }\n}\n\nexport class BooleanField extends BooleanExpression {\n  readonly expressionType: ExpressionType = 'Field';\n  constructor(readonly _expr: Field) {\n    super();\n  }\n}\n\n/**\n * SnippetExpression extends from FunctionExpression because it\n * supports options and requires the options util.\n */\nexport class SnippetExpression extends FunctionExpression {\n  /**\n   * @private\n   * @internal\n   */\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      maxSnippetWidth: {\n        serverName: 'max_snippet_width'\n      },\n      maxSnippets: {\n        serverName: 'max_snippets'\n      },\n      separator: {\n        serverName: 'separator'\n      }\n    });\n  }\n\n  /**\n   * @hideconstructor\n   */\n  constructor(params: Expression[], options?: {}) {\n    super('snippet', params, 'snippet', options);\n  }\n}\n\n/**\n * Creates an aggregation that counts the number of stage inputs where the provided\n * boolean expression evaluates to true.\n *\n * @example\n * ```typescript\n * // Count the number of documents where 'is_active' field equals true\n * countIf(field(\"is_active\").equal(true)).as(\"numActiveDocuments\");\n * ```\n *\n * @param booleanExpr - The boolean expression to evaluate on each input.\n * @returns A new `AggregateFunction` representing the 'countIf' aggregation.\n */\nexport function countIf(booleanExpr: BooleanExpression): AggregateFunction {\n  return booleanExpr.countIf();\n}\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index 1.\n * arrayGet('tags', 1);\n * ```\n *\n * @param arrayField - The name of the array field.\n * @param offset - The index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayField: string,\n  offset: number\n): FunctionExpression;\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index specified by field\n * // 'favoriteTag'.\n * arrayGet('tags', field('favoriteTag'));\n * ```\n *\n * @param arrayField - The name of the array field.\n * @param offsetExpr - An `Expression` evaluating to the index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayField: string,\n  offsetExpr: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index 1.\n * arrayGet(field('tags'), 1);\n * ```\n *\n * @param arrayExpression - An `Expression` evaluating to an array.\n * @param offset - The index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayExpression: Expression,\n  offset: number\n): FunctionExpression;\n\n/**\n * Creates an expression that indexes into an array from the beginning or end\n * and return the element. If the offset exceeds the array length, an error is\n * returned. A negative offset, starts from the end.\n *\n * @example\n * ```typescript\n * // Return the value in the tags field array at index specified by field\n * // 'favoriteTag'.\n * arrayGet(field('tags'), field('favoriteTag'));\n * ```\n *\n * @param arrayExpression - An `Expression` evaluating to an array.\n * @param offsetExpr - An `Expression` evaluating to the index of the element to return.\n * @returns A new `Expression` representing the 'arrayGet' operation.\n */\nexport function arrayGet(\n  arrayExpression: Expression,\n  offsetExpr: Expression\n): FunctionExpression;\nexport function arrayGet(\n  array: Expression | string,\n  offset: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayGet(valueToDefaultExpr(offset));\n}\n\n/**\n *\n * Creates an expression that checks if a given expression produces an error.\n *\n * @example\n * ```typescript\n * // Check if the result of a calculation is an error\n * isError(field(\"title\").arrayContains(1));\n * ```\n *\n * @param value - The expression to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isError' check.\n */\nexport function isError(value: Expression): BooleanExpression {\n  return value.isError().asBoolean();\n}\n\n/**\n *\n * Creates an expression that returns the `catch` argument if there is an\n * error, else return the result of the `try` argument evaluation.\n *\n * This overload is useful when a BooleanExpression is required.\n *\n * @example\n * ```typescript\n * // Create an expression that protects against a divide by zero error\n * // but always returns a boolean expression.\n * ifError(constant(50).divide(field('length')).greaterThan(1), constant(false));\n * ```\n *\n * @param tryExpr - The try expression.\n * @param catchExpr - The catch expression that will be evaluated and\n * returned if the tryExpr produces an error.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n */\nexport function ifError(\n  tryExpr: BooleanExpression,\n  catchExpr: BooleanExpression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that returns the `catch` argument if there is an\n * error, else return the result of the `try` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the first item in the title field arrays, or returns\n * // the entire title field if the array is empty or the field is another type.\n * ifError(field(\"title\").arrayGet(0), field(\"title\"));\n * ```\n *\n * @param tryExpr - The try expression.\n * @param catchExpr - The catch expression that will be evaluated and\n * returned if the tryExpr produces an error.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n */\nexport function ifError(\n  tryExpr: Expression,\n  catchExpr: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the `catch` argument if there is an\n * error, else return the result of the `try` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the first item in the title field arrays, or returns\n * // \"Default Title\"\n * ifError(field(\"title\").arrayGet(0), \"Default Title\");\n * ```\n *\n * @param tryExpr - The try expression.\n * @param catchValue - The value that will be returned if the tryExpr produces an\n * error.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation.\n */\nexport function ifError(\n  tryExpr: Expression,\n  catchValue: unknown\n): FunctionExpression;\n\nexport function ifError(\n  tryExpr: Expression,\n  catchValue: unknown\n): FunctionExpression | BooleanExpression {\n  if (\n    tryExpr instanceof BooleanExpression &&\n    catchValue instanceof BooleanExpression\n  ) {\n    return tryExpr.ifError(catchValue).asBoolean();\n  } else {\n    return tryExpr.ifError(valueToDefaultExpr(catchValue));\n  }\n}\n\n/**\n *\n * Creates an expression that returns `true` if a value is absent. Otherwise,\n * returns `false` even if the value is `null`.\n *\n * @example\n * ```typescript\n * // Check if the field `value` is absent.\n * isAbsent(field(\"value\"));\n * ```\n *\n * @param value - The expression to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isAbsent' check.\n */\nexport function isAbsent(value: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that returns `true` if a field is absent. Otherwise,\n * returns `false` even if the field value is `null`.\n *\n * @example\n * ```typescript\n * // Check if the field `value` is absent.\n * isAbsent(\"value\");\n * ```\n *\n * @param field - The field to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isAbsent' check.\n */\nexport function isAbsent(field: string): BooleanExpression;\nexport function isAbsent(value: Expression | string): BooleanExpression {\n  return fieldOrExpression(value).isAbsent();\n}\n\n/**\n *\n * Creates an expression that removes a key from the map at the specified field name.\n *\n * @example\n * ```\n * // Removes the key 'city' field from the map in the address field of the input document.\n * mapRemove('address', 'city');\n * ```\n *\n * @param mapField - The name of a field containing a map value.\n * @param key - The name of the key to remove from the input map.\n */\nexport function mapRemove(mapField: string, key: string): FunctionExpression;\n/**\n *\n * Creates an expression that removes a key from the map produced by evaluating an expression.\n *\n * @example\n * ```\n * // Removes the key 'baz' from the input map.\n * mapRemove(map({foo: 'bar', baz: true}), 'baz');\n * @example\n * ```\n *\n * @param mapExpr - An expression return a map value.\n * @param key - The name of the key to remove from the input map.\n */\nexport function mapRemove(mapExpr: Expression, key: string): FunctionExpression;\n/**\n *\n * Creates an expression that removes a key from the map at the specified field name.\n *\n * @example\n * ```\n * // Removes the key 'city' field from the map in the address field of the input document.\n * mapRemove('address', constant('city'));\n * ```\n *\n * @param mapField - The name of a field containing a map value.\n * @param keyExpr - An expression that produces the name of the key to remove from the input map.\n */\nexport function mapRemove(\n  mapField: string,\n  keyExpr: Expression\n): FunctionExpression;\n/**\n *\n * Creates an expression that removes a key from the map produced by evaluating an expression.\n *\n * @example\n * ```\n * // Removes the key 'baz' from the input map.\n * mapRemove(map({foo: 'bar', baz: true}), constant('baz'));\n * @example\n * ```\n *\n * @param mapExpr - An expression return a map value.\n * @param keyExpr - An expression that produces the name of the key to remove from the input map.\n */\nexport function mapRemove(\n  mapExpr: Expression,\n  keyExpr: Expression\n): FunctionExpression;\n\nexport function mapRemove(\n  mapExpr: Expression | string,\n  stringExpr: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(mapExpr).mapRemove(valueToDefaultExpr(stringExpr));\n}\n\n/**\n *\n * Creates an expression that merges multiple map values.\n *\n * @example\n * ```\n * // Merges the map in the settings field with, a map literal, and a map in\n * // that is conditionally returned by another expression\n * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {})\n * ```\n *\n * @param mapField - Name of a field containing a map value that will be merged.\n * @param secondMap - A required second map to merge. Represented as a literal or\n * an expression that returns a map.\n * @param otherMaps - Optional additional maps to merge. Each map is represented\n * as a literal or an expression that returns a map.\n */\nexport function mapMerge(\n  mapField: string,\n  secondMap: Record<string, unknown> | Expression,\n  ...otherMaps: Array<Record<string, unknown> | Expression>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that merges multiple map values.\n *\n * @example\n * ```\n * // Merges the map in the settings field with, a map literal, and a map in\n * // that is conditionally returned by another expression\n * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {})\n * ```\n *\n * @param firstMap - An expression or literal map value that will be merged.\n * @param secondMap - A required second map to merge. Represented as a literal or\n * an expression that returns a map.\n * @param otherMaps - Optional additional maps to merge. Each map is represented\n * as a literal or an expression that returns a map.\n */\nexport function mapMerge(\n  firstMap: Record<string, unknown> | Expression,\n  secondMap: Record<string, unknown> | Expression,\n  ...otherMaps: Array<Record<string, unknown> | Expression>\n): FunctionExpression;\n\nexport function mapMerge(\n  firstMap: string | Record<string, unknown> | Expression,\n  secondMap: Record<string, unknown> | Expression,\n  ...otherMaps: Array<Record<string, unknown> | Expression>\n): FunctionExpression {\n  const secondMapExpr = valueToDefaultExpr(secondMap);\n  const otherMapExprs = otherMaps.map(valueToDefaultExpr);\n  return fieldOrExpression(firstMap).mapMerge(secondMapExpr, ...otherMapExprs);\n}\n\n/**\n *\n * Creates an expression that returns the document ID from a path.\n *\n * @example\n * ```typescript\n * // Get the document ID from a path.\n * documentId(myDocumentReference);\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.\n */\nexport function documentId(\n  documentPath: string | DocumentReference\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the document ID from a path.\n *\n * @example\n * ```typescript\n * // Get the document ID from a path.\n * documentId(field(\"__path__\"));\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.\n */\nexport function documentId(documentPathExpr: Expression): FunctionExpression;\n\nexport function documentId(\n  documentPath: Expression | string | DocumentReference\n): FunctionExpression {\n  // @ts-ignore\n  const documentPathExpr = valueToDefaultExpr(documentPath);\n  return documentPathExpr.documentId();\n}\n\n/**\n *\n * Creates an expression that returns the parent document reference of a document reference.\n *\n * @example\n * ```typescript\n * // Get the parent document reference of a document reference.\n * parent(myDocumentReference);\n * ```\n *\n * @param documentPath - A string path or DocumentReference to get the parent from.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.\n */\nexport function parent(\n  documentPath: string | DocumentReference\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the parent document reference of a document reference.\n *\n * @example\n * ```typescript\n * // Get the parent document reference of a document reference.\n * parent(field(\"__path__\"));\n * ```\n *\n * @param documentPathExpr - An Expression evaluating to a document reference.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.\n */\nexport function parent(documentPathExpr: Expression): FunctionExpression;\n\nexport function parent(\n  documentPath: Expression | string | DocumentReference\n): FunctionExpression {\n  const documentPathExpr = valueToDefaultExpr(documentPath);\n  return documentPathExpr.parent();\n}\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param field - The name of a field containing a string or byte array to compute the substring from.\n * @param position - Index of the first character of the substring.\n * @param length - Length of the substring.\n */\nexport function substring(\n  field: string,\n  position: number,\n  length?: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param input - An expression returning a string or byte array to compute the substring from.\n * @param position - Index of the first character of the substring.\n * @param length - Length of the substring.\n */\nexport function substring(\n  input: Expression,\n  position: number,\n  length?: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param field - The name of a field containing a string or byte array to compute the substring from.\n * @param position - An expression that returns the index of the first character of the substring.\n * @param length - An expression that returns the length of the substring.\n */\nexport function substring(\n  field: string,\n  position: Expression,\n  length?: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns a substring of a string or byte array.\n *\n * @param input - An expression returning a string or byte array to compute the substring from.\n * @param position - An expression that returns the index of the first character of the substring.\n * @param length - An expression that returns the length of the substring.\n */\nexport function substring(\n  input: Expression,\n  position: Expression,\n  length?: Expression\n): FunctionExpression;\n\nexport function substring(\n  field: Expression | string,\n  position: Expression | number,\n  length?: Expression | number\n): FunctionExpression {\n  const fieldExpr = fieldOrExpression(field);\n  const positionExpr = valueToDefaultExpr(position);\n  const lengthExpr =\n    length === undefined ? undefined : valueToDefaultExpr(length);\n  return fieldExpr.substring(positionExpr, lengthExpr);\n}\n\n/**\n *\n * Creates an expression that adds two expressions together.\n *\n * @example\n * ```typescript\n * // Add the value of the 'quantity' field and the 'reserve' field.\n * add(field(\"quantity\"), field(\"reserve\"));\n * ```\n *\n * @param first - The first expression to add.\n * @param second - The second expression or literal to add.\n * @param others - Optional other expressions or literals to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the addition operation.\n */\nexport function add(\n  first: Expression,\n  second: Expression | unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that adds a field's value to an expression.\n *\n * @example\n * ```typescript\n * // Add the value of the 'quantity' field and the 'reserve' field.\n * add(\"quantity\", field(\"reserve\"));\n * ```\n *\n * @param fieldName - The name of the field containing the value to add.\n * @param second - The second expression or literal to add.\n * @param others - Optional other expressions or literals to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the addition operation.\n */\nexport function add(\n  fieldName: string,\n  second: Expression | unknown\n): FunctionExpression;\n\nexport function add(\n  first: Expression | string,\n  second: Expression | unknown\n): FunctionExpression {\n  return fieldOrExpression(first).add(valueToDefaultExpr(second));\n}\n\n/**\n *\n * Creates an expression that subtracts two expressions.\n *\n * @example\n * ```typescript\n * // Subtract the 'discount' field from the 'price' field\n * subtract(field(\"price\"), field(\"discount\"));\n * ```\n *\n * @param left - The expression to subtract from.\n * @param right - The expression to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(\n  left: Expression,\n  right: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a constant value from an expression.\n *\n * @example\n * ```typescript\n * // Subtract the constant value 2 from the 'value' field\n * subtract(field(\"value\"), 2);\n * ```\n *\n * @param expression - The expression to subtract from.\n * @param value - The constant value to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(\n  expression: Expression,\n  value: unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts an expression from a field's value.\n *\n * @example\n * ```typescript\n * // Subtract the 'discount' field from the 'price' field\n * subtract(\"price\", field(\"discount\"));\n * ```\n *\n * @param fieldName - The field name to subtract from.\n * @param expression - The expression to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(\n  fieldName: string,\n  expression: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a constant value from a field's value.\n *\n * @example\n * ```typescript\n * // Subtract 20 from the value of the 'total' field\n * subtract(\"total\", 20);\n * ```\n *\n * @param fieldName - The field name to subtract from.\n * @param value - The constant value to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation.\n */\nexport function subtract(fieldName: string, value: unknown): FunctionExpression;\nexport function subtract(\n  left: Expression | string,\n  right: Expression | unknown\n): FunctionExpression {\n  const normalizedLeft = typeof left === 'string' ? field(left) : left;\n  const normalizedRight = valueToDefaultExpr(right);\n  return normalizedLeft.subtract(normalizedRight);\n}\n\n/**\n *\n * Creates an expression that multiplies two expressions together.\n *\n * @example\n * ```typescript\n * // Multiply the 'quantity' field by the 'price' field\n * multiply(field(\"quantity\"), field(\"price\"));\n * ```\n *\n * @param first - The first expression to multiply.\n * @param second - The second expression or literal to multiply.\n * @param others - Optional additional expressions or literals to multiply.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the multiplication operation.\n */\nexport function multiply(\n  first: Expression,\n  second: Expression | unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that multiplies a field's value by an expression.\n *\n * @example\n * ```typescript\n * // Multiply the 'quantity' field by the 'price' field\n * multiply(\"quantity\", field(\"price\"));\n * ```\n *\n * @param fieldName - The name of the field containing the value to add.\n * @param second - The second expression or literal to add.\n * @param others - Optional other expressions or literals to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the multiplication operation.\n */\nexport function multiply(\n  fieldName: string,\n  second: Expression | unknown\n): FunctionExpression;\n\nexport function multiply(\n  first: Expression | string,\n  second: Expression | unknown\n): FunctionExpression {\n  return fieldOrExpression(first).multiply(valueToDefaultExpr(second));\n}\n\n/**\n *\n * Creates an expression that divides two expressions.\n *\n * @example\n * ```typescript\n * // Divide the 'total' field by the 'count' field\n * divide(field(\"total\"), field(\"count\"));\n * ```\n *\n * @param left - The expression to be divided.\n * @param right - The expression to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(left: Expression, right: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that divides an expression by a constant value.\n *\n * @example\n * ```typescript\n * // Divide the 'value' field by 10\n * divide(field(\"value\"), 10);\n * ```\n *\n * @param expression - The expression to be divided.\n * @param value - The constant value to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(\n  expression: Expression,\n  value: unknown\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that divides a field's value by an expression.\n *\n * @example\n * ```typescript\n * // Divide the 'total' field by the 'count' field\n * divide(\"total\", field(\"count\"));\n * ```\n *\n * @param fieldName - The field name to be divided.\n * @param expressions - The expression to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(\n  fieldName: string,\n  expressions: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that divides a field's value by a constant value.\n *\n * @example\n * ```typescript\n * // Divide the 'value' field by 10\n * divide(\"value\", 10);\n * ```\n *\n * @param fieldName - The field name to be divided.\n * @param value - The constant value to divide by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation.\n */\nexport function divide(fieldName: string, value: unknown): FunctionExpression;\nexport function divide(\n  left: Expression | string,\n  right: Expression | unknown\n): FunctionExpression {\n  const normalizedLeft = typeof left === 'string' ? field(left) : left;\n  const normalizedRight = valueToDefaultExpr(right);\n  return normalizedLeft.divide(normalizedRight);\n}\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing two expressions.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 'field2'.\n * mod(field(\"field1\"), field(\"field2\"));\n * ```\n *\n * @param left - The dividend expression.\n * @param right - The divisor expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(left: Expression, right: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 5.\n * mod(field(\"field1\"), 5);\n * ```\n *\n * @param expression - The dividend expression.\n * @param value - The divisor constant.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(expression: Expression, value: unknown): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 'field2'.\n * mod(\"field1\", field(\"field2\"));\n * ```\n *\n * @param fieldName - The dividend field name.\n * @param expression - The divisor expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(\n  fieldName: string,\n  expression: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant.\n *\n * @example\n * ```typescript\n * // Calculate the remainder of dividing 'field1' by 5.\n * mod(\"field1\", 5);\n * ```\n *\n * @param fieldName - The dividend field name.\n * @param value - The divisor constant.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation.\n */\nexport function mod(fieldName: string, value: unknown): FunctionExpression;\nexport function mod(\n  left: Expression | string,\n  right: Expression | unknown\n): FunctionExpression {\n  const normalizedLeft = typeof left === 'string' ? field(left) : left;\n  const normalizedRight = valueToDefaultExpr(right);\n  return normalizedLeft.mod(normalizedRight);\n}\n\n/**\n *\n * Creates an expression that creates a Firestore map value from an input object.\n *\n * @example\n * ```typescript\n * // Create a map from the input object and reference the 'baz' field value from the input document.\n * map({foo: 'bar', baz: field('baz')}).as('data');\n * ```\n *\n * @param elements - The input map to evaluate in the expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the map function.\n */\nexport function map(elements: Record<string, unknown>): FunctionExpression {\n  return _map(elements, 'map');\n}\nexport function _map(\n  elements: Record<string, unknown>,\n  methodName: string | undefined\n): FunctionExpression {\n  const result: Expression[] = [];\n  for (const key in elements) {\n    if (Object.prototype.hasOwnProperty.call(elements, key)) {\n      const value = elements[key];\n      result.push(constant(key));\n      result.push(valueToDefaultExpr(value));\n    }\n  }\n  return new FunctionExpression('map', result, 'map');\n}\n\n/**\n * Internal use only\n * Converts a plainObject to a mapValue in the proto representation,\n * rather than a functionValue+map that is the result of the map(...) function.\n * This behaves different from constant(plainObject) because it\n * traverses the input object, converts values in the object to expressions,\n * and calls _readUserData on each of these expressions.\n * @private\n * @internal\n * @param plainObject\n */\nexport function _mapValue(plainObject: Record<string, unknown>): MapValue {\n  const result: Map<string, Expression> = new Map<string, Expression>();\n  for (const key in plainObject) {\n    if (Object.prototype.hasOwnProperty.call(plainObject, key)) {\n      const value = plainObject[key];\n      result.set(key, valueToDefaultExpr(value));\n    }\n  }\n  return new MapValue(result, undefined);\n}\n\n/**\n *\n * Creates an expression that creates a Firestore array value from an input array.\n *\n * @example\n * ```typescript\n * // Create an array value from the input array and reference the 'baz' field value from the input document.\n * array(['bar', field('baz')]).as('foo');\n * ```\n *\n * @param elements - The input array to evaluate in the expression.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the array function.\n */\nexport function array(elements: unknown[]): FunctionExpression {\n  return _array(elements, 'array');\n}\nexport function _array(\n  elements: unknown[],\n  methodName: string | undefined\n): FunctionExpression {\n  return new FunctionExpression(\n    'array',\n    elements.map(element => valueToDefaultExpr(element)),\n    methodName\n  );\n}\n\n/**\n *\n * Creates an expression that checks if two expressions are equal.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is equal to an expression\n * equal(field(\"age\"), field(\"minAge\").add(10));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(left: Expression, right: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is equal to 21\n * equal(field(\"age\"), 21);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is equal to the 'limit' field\n * equal(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'city' field is equal to string constant \"London\"\n * equal(\"city\", \"London\");\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the equality comparison.\n */\nexport function equal(fieldName: string, value: unknown): BooleanExpression;\nexport function equal(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.equal(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if two expressions are not equal.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to field 'finalState'\n * notEqual(field(\"status\"), field(\"finalState\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is not equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to \"completed\"\n * notEqual(field(\"status\"), \"completed\");\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to the value of 'expectedStatus'\n * notEqual(\"status\", field(\"expectedStatus\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'country' field is not equal to \"USA\"\n * notEqual(\"country\", \"USA\");\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the inequality comparison.\n */\nexport function notEqual(fieldName: string, value: unknown): BooleanExpression;\nexport function notEqual(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.notEqual(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is less than the second expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is less than 30\n * lessThan(field(\"age\"), field(\"limit\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is less than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is less than 30\n * lessThan(field(\"age\"), 30);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is less than an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is less than the 'limit' field\n * lessThan(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is less than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'price' field is less than 50\n * lessThan(\"price\", 50);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than comparison.\n */\nexport function lessThan(fieldName: string, value: unknown): BooleanExpression;\nexport function lessThan(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.lessThan(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is less than or equal to the second\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is less than or equal to 20\n * lessThan(field(\"quantity\"), field(\"limit\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is less than or equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is less than or equal to 20\n * lessThan(field(\"quantity\"), 20);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n * Creates an expression that checks if a field's value is less than or equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is less than or equal to the 'limit' field\n * lessThan(\"quantity\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is less than or equal to a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'score' field is less than or equal to 70\n * lessThan(\"score\", 70);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the less than or equal to comparison.\n */\nexport function lessThanOrEqual(\n  fieldName: string,\n  value: unknown\n): BooleanExpression;\nexport function lessThanOrEqual(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.lessThanOrEqual(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is greater than the second\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18\n * greaterThan(field(\"age\"), constant(9).add(9));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is greater than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18\n * greaterThan(field(\"age\"), 18);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than an expression.\n *\n * @example\n * ```typescript\n * // Check if the value of field 'age' is greater than the value of field 'limit'\n * greaterThan(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param expression - The expression to compare to.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  fieldName: string,\n  expression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than a constant value.\n *\n * @example\n * ```typescript\n * // Check if the 'price' field is greater than 100\n * greaterThan(\"price\", 100);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than comparison.\n */\nexport function greaterThan(\n  fieldName: string,\n  value: unknown\n): BooleanExpression;\nexport function greaterThan(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.greaterThan(rightExpr);\n}\n\n/**\n *\n * Creates an expression that checks if the first expression is greater than or equal to the\n * second expression.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is greater than or equal to the field \"threshold\"\n * greaterThanOrEqual(field(\"quantity\"), field(\"threshold\"));\n * ```\n *\n * @param left - The first expression to compare.\n * @param right - The second expression to compare.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  left: Expression,\n  right: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is greater than or equal to a constant\n * value.\n *\n * @example\n * ```typescript\n * // Check if the 'quantity' field is greater than or equal to 10\n * greaterThanOrEqual(field(\"quantity\"), 10);\n * ```\n *\n * @param expression - The expression to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  expression: Expression,\n  value: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than or equal to an expression.\n *\n * @example\n * ```typescript\n * // Check if the value of field 'age' is greater than or equal to the value of field 'limit'\n * greaterThanOrEqual(\"age\", field(\"limit\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The expression to compare to.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  fieldName: string,\n  value: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is greater than or equal to a constant\n * value.\n *\n * @example\n * ```typescript\n * // Check if the 'score' field is greater than or equal to 80\n * greaterThanOrEqual(\"score\", 80);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param value - The constant value to compare to.\n * @returns A new `Expression` representing the greater than or equal to comparison.\n */\nexport function greaterThanOrEqual(\n  fieldName: string,\n  value: unknown\n): BooleanExpression;\nexport function greaterThanOrEqual(\n  left: Expression | string,\n  right: unknown\n): BooleanExpression {\n  const leftExpr = left instanceof Expression ? left : field(left);\n  const rightExpr = valueToDefaultExpr(right);\n  return leftExpr.greaterThanOrEqual(rightExpr);\n}\n\n/**\n *\n * Creates an expression that concatenates an array expression with other arrays.\n *\n * @example\n * ```typescript\n * // Combine the 'items' array with two new item arrays\n * arrayConcat(field(\"items\"), [field(\"newItems\"), field(\"otherItems\")]);\n * ```\n *\n * @param firstArray - The first array expression to concatenate to.\n * @param secondArray - The second array expression or array literal to concatenate to.\n * @param otherArrays - Optional additional array expressions or array literals to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated array.\n */\nexport function arrayConcat(\n  firstArray: Expression,\n  secondArray: Expression | unknown[],\n  ...otherArrays: Array<Expression | unknown[]>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that concatenates a field's array value with other arrays.\n *\n * @example\n * ```typescript\n * // Combine the 'items' array with two new item arrays\n * arrayConcat(\"items\", [field(\"newItems\"), field(\"otherItems\")]);\n * ```\n *\n * @param firstArrayField - The first array to concatenate to.\n * @param secondArray - The second array expression or array literal to concatenate to.\n * @param otherArrays - Optional additional array expressions or array literals to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated array.\n */\nexport function arrayConcat(\n  firstArrayField: string,\n  secondArray: Expression | unknown[],\n  ...otherArrays: Array<Expression | unknown[]>\n): FunctionExpression;\n\nexport function arrayConcat(\n  firstArray: Expression | string,\n  secondArray: Expression | unknown[],\n  ...otherArrays: Array<Expression | unknown[]>\n): FunctionExpression {\n  const exprValues = otherArrays.map(element => valueToDefaultExpr(element));\n  return fieldOrExpression(firstArray).arrayConcat(\n    fieldOrExpression(secondArray),\n    ...exprValues\n  );\n}\n\n/**\n *\n * Creates an expression that checks if an array expression contains a specific element.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains the value of field 'selectedColor'\n * arrayContains(field(\"colors\"), field(\"selectedColor\"));\n * ```\n *\n * @param array - The array expression to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  array: Expression,\n  element: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an array expression contains a specific element.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains \"red\"\n * arrayContains(field(\"colors\"), \"red\");\n * ```\n *\n * @param array - The array expression to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  array: Expression,\n  element: unknown\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains a specific element.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains the value of field 'selectedColor'\n * arrayContains(\"colors\", field(\"selectedColor\"));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  fieldName: string,\n  element: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains a specific value.\n *\n * @example\n * ```typescript\n * // Check if the 'colors' array contains \"red\"\n * arrayContains(\"colors\", \"red\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @param element - The element to search for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison.\n */\nexport function arrayContains(\n  fieldName: string,\n  element: unknown\n): BooleanExpression;\nexport function arrayContains(\n  array: Expression | string,\n  element: unknown\n): BooleanExpression {\n  const arrayExpr = fieldOrExpression(array);\n  const elementExpr = valueToDefaultExpr(element);\n  return arrayExpr.arrayContains(elementExpr);\n}\n\n/**\n *\n * Creates an expression that checks if an array expression contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'categories' array contains either values from field \"cate1\" or \"Science\"\n * arrayContainsAny(field(\"categories\"), [field(\"cate1\"), \"Science\"]);\n * ```\n *\n * @param array - The array expression to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  array: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'groups' array contains either the value from the 'userGroup' field\n * // or the value \"guest\"\n * arrayContainsAny(\"categories\", [field(\"cate1\"), \"Science\"]);\n * ```\n *\n * @param fieldName - The field name to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an array expression contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'categories' array contains either values from field \"cate1\" or \"Science\"\n * arrayContainsAny(field(\"categories\"), array([field(\"cate1\"), \"Science\"]));\n * ```\n *\n * @param array - The array expression to check.\n * @param values - An expression that evaluates to an array, whose elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  array: Expression,\n  values: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains any of the specified\n * elements.\n *\n * @example\n * ```typescript\n * // Check if the 'groups' array contains either the value from the 'userGroup' field\n * // or the value \"guest\"\n * arrayContainsAny(\"categories\", array([field(\"cate1\"), \"Science\"]));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param values - An expression that evaluates to an array, whose elements to check for in the array field.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison.\n */\nexport function arrayContainsAny(\n  fieldName: string,\n  values: Expression\n): BooleanExpression;\nexport function arrayContainsAny(\n  array: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(array).arrayContainsAny(values);\n}\n\n/**\n *\n * Creates an expression that checks if an array expression contains all the specified elements.\n *\n * @example\n * ```typescript\n * // Check if the \"tags\" array contains all of the values: \"SciFi\", \"Adventure\", and the value from field \"tag1\"\n * arrayContainsAll(field(\"tags\"), [field(\"tag1\"), constant(\"SciFi\"), \"Adventure\"]);\n * ```\n *\n * @param array - The array expression to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  array: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains all the specified values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'tags' array contains both of the values from field 'tag1', the value \"SciFi\", and \"Adventure\"\n * arrayContainsAll(\"tags\", [field(\"tag1\"), \"SciFi\", \"Adventure\"]);\n * ```\n *\n * @param fieldName - The field name to check.\n * @param values - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an array expression contains all the specified elements.\n *\n * @example\n * ```typescript\n * // Check if the \"tags\" array contains all of the values: \"SciFi\", \"Adventure\", and the value from field \"tag1\"\n * arrayContainsAll(field(\"tags\"), [field(\"tag1\"), constant(\"SciFi\"), \"Adventure\"]);\n * ```\n *\n * @param array - The array expression to check.\n * @param arrayExpression - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  array: Expression,\n  arrayExpression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's array value contains all the specified values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'tags' array contains both of the values from field 'tag1', the value \"SciFi\", and \"Adventure\"\n * arrayContainsAll(\"tags\", [field(\"tag1\"), \"SciFi\", \"Adventure\"]);\n * ```\n *\n * @param fieldName - The field name to check.\n * @param arrayExpression - The elements to check for in the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison.\n */\nexport function arrayContainsAll(\n  fieldName: string,\n  arrayExpression: Expression\n): BooleanExpression;\nexport function arrayContainsAll(\n  array: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(array).arrayContainsAll(values);\n}\n\n/**\n *\n * Creates an expression that calculates the length of an array in a specified field.\n *\n * @example\n * ```typescript\n * // Get the number of items in field 'cart'\n * arrayLength('cart');\n * ```\n *\n * @param fieldName - The name of the field containing an array to calculate the length of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function arrayLength(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the length of an array expression.\n *\n * @example\n * ```typescript\n * // Get the number of items in the 'cart' array\n * arrayLength(field(\"cart\"));\n * ```\n *\n * @param array - The array expression to calculate the length of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function arrayLength(array: Expression): FunctionExpression;\nexport function arrayLength(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayLength();\n}\n\n/**\n *\n * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n * equalAny(field(\"category\"), [constant(\"Electronics\"), field(\"primaryType\")]);\n * ```\n *\n * @param expression - The expression whose results to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  expression: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is equal to any of the provided values.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is set to a value in the disabledCategories field\n * equalAny(field(\"category\"), field('disabledCategories'));\n * ```\n *\n * @param expression - The expression whose results to compare.\n * @param arrayExpression - An expression that evaluates to an array, whose elements to check for equality to the input.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  expression: Expression,\n  arrayExpression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to any of the provided values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n * equalAny(\"category\", [constant(\"Electronics\"), field(\"primaryType\")]);\n * ```\n *\n * @param fieldName - The field to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is equal to any of the provided values or\n * expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'category' field is either \"Electronics\" or value of field 'primaryType'\n * equalAny(\"category\", [\"Electronics\", field(\"primaryType\")]);\n * ```\n *\n * @param fieldName - The field to compare.\n * @param arrayExpression - An expression that evaluates to an array, whose elements to check for equality to the input field.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison.\n */\nexport function equalAny(\n  fieldName: string,\n  arrayExpression: Expression\n): BooleanExpression;\nexport function equalAny(\n  element: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(element).equalAny(values);\n}\n\n/**\n *\n * Creates an expression that checks if an expression is not equal to any of the provided values\n * or expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is neither \"pending\" nor the value of 'rejectedStatus'\n * notEqualAny(field(\"status\"), [\"pending\", field(\"rejectedStatus\")]);\n * ```\n *\n * @param element - The expression to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  element: Expression,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to any of the provided values\n * or expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is neither \"pending\" nor the value of 'rejectedStatus'\n * notEqualAny(\"status\", [constant(\"pending\"), field(\"rejectedStatus\")]);\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param values - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  fieldName: string,\n  values: Array<Expression | unknown>\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if an expression is not equal to any of the provided values\n * or expressions.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is neither \"pending\" nor the value of the field 'rejectedStatus'\n * notEqualAny(field(\"status\"), [\"pending\", field(\"rejectedStatus\")]);\n * ```\n *\n * @param element - The expression to compare.\n * @param arrayExpression - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  element: Expression,\n  arrayExpression: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression.\n *\n * @example\n * ```typescript\n * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses'\n * notEqualAny(\"status\", field(\"rejectedStatuses\"));\n * ```\n *\n * @param fieldName - The field name to compare.\n * @param arrayExpression - The values to check against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison.\n */\nexport function notEqualAny(\n  fieldName: string,\n  arrayExpression: Expression\n): BooleanExpression;\n\nexport function notEqualAny(\n  element: Expression | string,\n  values: unknown[] | Expression\n): BooleanExpression {\n  // @ts-ignore implementation accepts both types\n  return fieldOrExpression(element).notEqualAny(values);\n}\n\n/**\n *\n * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions.\n *\n * @example\n * ```typescript\n * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is \"London\",\n * // or 'status' is \"active\".\n * const condition = xor(\n *     greaterThan(\"age\", 18),\n *     equal(\"city\", \"London\"),\n *     equal(\"status\", \"active\"));\n * ```\n *\n * @param first - The first condition.\n * @param second - The second condition.\n * @param additionalConditions - Additional conditions to 'XOR' together.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'XOR' operation.\n */\nexport function xor(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...additionalConditions: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'xor',\n    [first, second, ...additionalConditions],\n    'xor'\n  ).asBoolean();\n}\n\n/**\n *\n * Creates a conditional expression that evaluates to a 'then' expression if a condition is true\n * and an 'else' expression if the condition is false.\n *\n * @example\n * ```typescript\n * // If 'age' is greater than 18, return \"Adult\"; otherwise, return \"Minor\".\n * conditional(\n *     greaterThan(\"age\", 18), constant(\"Adult\"), constant(\"Minor\"));\n * ```\n *\n * @param condition - The condition to evaluate.\n * @param thenExpr - The expression to evaluate if the condition is true.\n * @param elseExpr - The expression to evaluate if the condition is false.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.\n */\nexport function conditional(\n  condition: BooleanExpression,\n  thenExpr: Expression,\n  elseExpr: Expression\n): FunctionExpression {\n  return new FunctionExpression(\n    'conditional',\n    [condition, thenExpr, elseExpr],\n    'conditional'\n  );\n}\n\n/**\n *\n * Creates an expression that negates a filter condition.\n *\n * @example\n * ```typescript\n * // Find documents where the 'completed' field is NOT true\n * not(equal(\"completed\", true));\n * ```\n *\n * @param booleanExpr - The filter condition to negate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.\n */\nexport function not(booleanExpr: BooleanExpression): BooleanExpression {\n  return booleanExpr.not();\n}\n\n/**\n *\n * Creates an expression that returns the largest value between multiple input\n * expressions or literal values. Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the largest value between the 'field1' field, the 'field2' field,\n * // and 1000\n * logicalMaximum(field(\"field1\"), field(\"field2\"), 1000);\n * ```\n *\n * @param first - The first operand expression.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.\n */\nexport function logicalMaximum(\n  first: Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest value between multiple input\n * expressions or literal values. Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the largest value between the 'field1' field, the 'field2' field,\n * // and 1000.\n * logicalMaximum(\"field1\", field(\"field2\"), 1000);\n * ```\n *\n * @param fieldName - The first operand field name.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.\n */\nexport function logicalMaximum(\n  fieldName: string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\nexport function logicalMaximum(\n  first: Expression | string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return fieldOrExpression(first).logicalMaximum(\n    valueToDefaultExpr(second),\n    ...others.map(value => valueToDefaultExpr(value))\n  );\n}\n\n/**\n *\n * Creates an expression that returns the smallest value between multiple input\n * expressions and literal values. Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the smallest value between the 'field1' field, the 'field2' field,\n * // and 1000.\n * logicalMinimum(field(\"field1\"), field(\"field2\"), 1000);\n * ```\n *\n * @param first - The first operand expression.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.\n */\nexport function logicalMinimum(\n  first: Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest value between a field's value\n * and other input expressions or literal values.\n * Based on Firestore's value type ordering.\n *\n * @example\n * ```typescript\n * // Returns the smallest value between the 'field1' field, the 'field2' field,\n * // and 1000.\n * logicalMinimum(\"field1\", field(\"field2\"), 1000);\n * ```\n *\n * @param fieldName - The first operand field name.\n * @param second - The second expression or literal.\n * @param others - Optional additional expressions or literals.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.\n */\nexport function logicalMinimum(\n  fieldName: string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\nexport function logicalMinimum(\n  first: Expression | string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return fieldOrExpression(first).logicalMinimum(\n    valueToDefaultExpr(second),\n    ...others.map(value => valueToDefaultExpr(value))\n  );\n}\n\n/**\n *\n * Creates an expression that checks if a field exists.\n *\n * @example\n * ```typescript\n * // Check if the document has a field named \"phoneNumber\"\n * exists(field(\"phoneNumber\"));\n * ```\n *\n * @param value - An expression evaluates to the name of the field to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'exists' check.\n */\nexport function exists(value: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field exists.\n *\n * @example\n * ```typescript\n * // Check if the document has a field named \"phoneNumber\"\n * exists(\"phoneNumber\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'exists' check.\n */\nexport function exists(fieldName: string): BooleanExpression;\nexport function exists(valueOrField: Expression | string): BooleanExpression {\n  return fieldOrExpression(valueOrField).exists();\n}\n\n/**\n *\n * Creates an expression that reverses a string.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * reverse(field(\"myString\"));\n * ```\n *\n * @param stringExpression - An expression evaluating to a string value, which will be reversed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function reverse(stringExpression: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that reverses a string value in the specified field.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * reverse(\"myString\");\n * ```\n *\n * @param field - The name of the field representing the string to reverse.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function reverse(field: string): FunctionExpression;\nexport function reverse(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).reverse();\n}\n\n/**\n *\n * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob.\n *\n * @example\n * ```typescript\n * // Calculate the length of the 'myString' field in bytes.\n * byteLength(field(\"myString\"));\n * ```\n *\n * @param expr - The expression representing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.\n */\nexport function byteLength(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob.\n *\n * @example\n * ```typescript\n * // Calculate the length of the 'myString' field in bytes.\n * byteLength(\"myString\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.\n */\nexport function byteLength(fieldName: string): FunctionExpression;\nexport function byteLength(expr: Expression | string): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.byteLength();\n}\n\n/**\n * Creates an expression that reverses an array.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myArray' field.\n * arrayReverse(\"myArray\");\n * ```\n *\n * @param fieldName - The name of the field to reverse.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.\n */\nexport function arrayReverse(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that reverses an array.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myArray' field.\n * arrayReverse(field(\"myArray\"));\n * ```\n *\n * @param arrayExpression - An expression evaluating to an array value, which will be reversed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.\n */\nexport function arrayReverse(arrayExpression: Expression): FunctionExpression;\nexport function arrayReverse(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).arrayReverse();\n}\n\n/**\n * Creates an expression that computes e to the power of the expression's result.\n *\n * @example\n * ```typescript\n * // Compute e to the power of 2.\n * exp(constant(2));\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.\n */\nexport function exp(expression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that computes e to the power of the expression's result.\n *\n * @example\n * ```typescript\n * // Compute e to the power of the 'value' field.\n * exp('value');\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.\n */\nexport function exp(fieldName: string): FunctionExpression;\n\nexport function exp(\n  expressionOrFieldName: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(expressionOrFieldName).exp();\n}\n\n/**\n * Creates an expression that computes the ceiling of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the ceiling of the 'price' field.\n * ceil(\"price\");\n * ```\n *\n * @param fieldName - The name of the field to compute the ceiling of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.\n */\nexport function ceil(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the ceiling of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the ceiling of the 'price' field.\n * ceil(field(\"price\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the ceiling will be computed for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.\n */\nexport function ceil(expression: Expression): FunctionExpression;\nexport function ceil(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).ceil();\n}\n\n/**\n * Creates an expression that computes the floor of a numeric value.\n *\n * @param expr - The expression to compute the floor of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.\n */\nexport function floor(expr: Expression): FunctionExpression;\n\n/**\n * Creates an expression that computes the floor of a numeric value.\n *\n * @param fieldName - The name of the field to compute the floor of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.\n */\nexport function floor(fieldName: string): FunctionExpression;\nexport function floor(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).floor();\n}\n\n/**\n * Creates an aggregation that counts the number of distinct values of a field.\n *\n * @param expr - The expression or field to count distinct values of.\n * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.\n */\nexport function countDistinct(expr: Expression | string): AggregateFunction {\n  return fieldOrExpression(expr).countDistinct();\n}\n\n/**\n *\n * Creates an expression that calculates the character length of a string field in UTF8.\n *\n * @example\n * ```typescript\n * // Get the character length of the 'name' field in UTF-8.\n * charLength(\"name\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string.\n */\nexport function charLength(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the character length of a string expression in UTF-8.\n *\n * @example\n * ```typescript\n * // Get the character length of the 'name' field in UTF-8.\n * charLength(field(\"name\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to calculate the length of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string.\n */\nexport function charLength(stringExpression: Expression): FunctionExpression;\nexport function charLength(value: Expression | string): FunctionExpression {\n  const valueExpr = fieldOrExpression(value);\n  return valueExpr.charLength();\n}\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison against a\n * field.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(\"title\", \"%guide%\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(fieldName: string, pattern: string): BooleanExpression;\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison against a\n * field.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(\"title\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(fieldName: string, pattern: Expression): BooleanExpression;\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(field(\"title\"), \"%guide%\");\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(\n  stringExpression: Expression,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that performs a case-sensitive wildcard string comparison.\n *\n * @example\n * ```typescript\n * // Check if the 'title' field contains the string \"guide\"\n * like(field(\"title\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The pattern to search for. You can use \"%\" as a wildcard character.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison.\n */\nexport function like(\n  stringExpression: Expression,\n  pattern: Expression\n): BooleanExpression;\nexport function like(\n  left: Expression | string,\n  pattern: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.like(patternExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a string field contains a specified regular expression as\n * a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(\"description\", \"(?i)example\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  fieldName: string,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string field contains a specified regular expression as\n * a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(\"description\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  fieldName: string,\n  pattern: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a specified regular\n * expression as a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(field(\"description\"), \"(?i)example\");\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  stringExpression: Expression,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a specified regular\n * expression as a substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\" (case-insensitive)\n * regexContains(field(\"description\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param pattern - The regular expression to use for the search.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function regexContains(\n  stringExpression: Expression,\n  pattern: Expression\n): BooleanExpression;\nexport function regexContains(\n  left: Expression | string,\n  pattern: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexContains(patternExpr);\n}\n\n/**\n *\n * Creates an expression that filters an array using a provided alias and predicate expression.\n *\n * @example\n * ```typescript\n * // Get a filtered array of the 'scores' field containing only elements greater than 50.\n * arrayFilter(\"scores\", \"score\", greaterThan(variable(\"score\"), 50));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param alias - The variable name to use for each element.\n * @param filter - The predicate boolean expression to evaluate for each element.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the filtered array.\n */\nexport function arrayFilter(\n  fieldName: string,\n  alias: string,\n  filter: BooleanExpression\n): FunctionExpression;\n\n/**\n * Creates an expression that filters an array using a provided alias and predicate expression.\n *\n * @example\n * ```typescript\n * // Filter \"scores\" to include only values greater than 50\n * arrayFilter(field(\"scores\"), \"score\", greaterThan(variable(\"score\"), 50));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param alias - The variable name to use for each element.\n * @param filter - The predicate boolean expression to filter by.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the filtered array.\n */\nexport function arrayFilter(\n  arrayExpression: Expression,\n  alias: string,\n  filter: BooleanExpression\n): FunctionExpression;\n\nexport function arrayFilter(\n  array: Expression | string,\n  alias: string,\n  filter: BooleanExpression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayFilter(alias, filter);\n}\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by multiplying each score by 10\n * arrayTransform(field(\"scores\"), \"score\", multiply(variable(\"score\"), 10));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param transform - The lambda expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransform(\n  arrayExpression: Expression,\n  elementAlias: string,\n  transform: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by multiplying each score by 10\n * arrayTransform(\"scores\", \"score\", multiply(variable(\"score\"), 10));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param transform - The expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransform(\n  fieldName: string,\n  elementAlias: string,\n  transform: Expression\n): FunctionExpression;\nexport function arrayTransform(\n  array: Expression | string,\n  elementAlias: string,\n  transform: Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayTransform(elementAlias, transform);\n}\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by adding the index to each score\n * arrayTransformWithIndex(field(\"scores\"), \"score\", \"i\", add(variable(\"score\"), variable(\"i\")));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param indexAlias - The variable name to use for the current index.\n * @param transform - The expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransformWithIndex(\n  arrayExpression: Expression,\n  elementAlias: string,\n  indexAlias: string,\n  transform: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.\n *\n * @example\n * ```typescript\n * // Transform \"scores\" array by adding the index to each score\n * arrayTransformWithIndex(\"scores\", \"score\", \"i\", add(variable(\"score\"), variable(\"i\")));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param elementAlias - The variable name to use for each element.\n * @param indexAlias - The variable name to use for the current index.\n * @param transform - The lambda expression used to transform the elements.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the transformed array.\n */\nexport function arrayTransformWithIndex(\n  fieldName: string,\n  elementAlias: string,\n  indexAlias: string,\n  transform: Expression\n): FunctionExpression;\nexport function arrayTransformWithIndex(\n  array: Expression | string,\n  elementAlias: string,\n  indexAlias: string,\n  transform: Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayTransformWithIndex(\n    elementAlias,\n    indexAlias,\n    transform\n  );\n}\n\n/**\n * Creates an expression that returns a slice of an array from `offset` with `length` elements.\n *\n * @example\n * ```typescript\n * // Get 5 elements from the 'items' array field starting from index 2\n * arraySlice(\"items\", 2, 5);\n *\n * // Get n elements from the 'items' array field starting from index 2\n * arraySlice(\"items\", 2, field(\"length\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param offset - The starting offset.\n * @param length - The optional length of the slice.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sliced array.\n */\nexport function arraySlice(\n  fieldName: string,\n  offset: number | Expression,\n  length?: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that returns a slice of an array from `offset` with `length` elements.\n *\n * @example\n * ```typescript\n * // Get 5 elements from an array expression starting from index 2\n * arraySlice(field(\"items\"), 2, 5);\n *\n * // Get n elements from an array expression starting from index 2\n * arraySlice(field(\"items\"), 2, field(\"length\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param offset - The starting offset.\n * @param length - The optional length of the slice.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sliced array.\n */\nexport function arraySlice(\n  arrayExpression: Expression,\n  offset: number | Expression,\n  length?: number | Expression\n): FunctionExpression;\nexport function arraySlice(\n  array: Expression | string,\n  offset: number | Expression,\n  length?: number | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arraySlice(offset, length);\n}\n\n/**\n * Creates an expression that returns the first element of an array.\n *\n * @example\n * ```typescript\n * // Get the first tag from the 'tags' array field\n * arrayFirst(\"tags\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first element.\n */\nexport function arrayFirst(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first element of an array.\n *\n * @example\n * ```typescript\n * // Get the first tag from the 'tags' array field\n * arrayFirst(field(\"tags\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first element.\n */\nexport function arrayFirst(arrayExpression: Expression): FunctionExpression;\nexport function arrayFirst(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayFirst();\n}\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first 3 tags from the 'tags' array field\n * arrayFirstN(\"tags\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first n tags from the 'tags' array field\n * arrayFirstN(\"tags\", field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first 3 elements from an array expression\n * arrayFirstN(field(\"tags\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the first n elements from an array expression\n * arrayFirstN(field(\"tags\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the first `n` elements.\n */\nexport function arrayFirstN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayFirstN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayFirstN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the last element of an array.\n *\n * @example\n * ```typescript\n * // Get the last tag from the 'tags' array field\n * arrayLast(\"tags\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last element.\n */\nexport function arrayLast(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last element of an array.\n *\n * @example\n * ```typescript\n * // Get the last tag from the 'tags' array field\n * arrayLast(field(\"tags\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last element.\n */\nexport function arrayLast(arrayExpression: Expression): FunctionExpression;\nexport function arrayLast(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayLast();\n}\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last 3 tags from the 'tags' array field\n * arrayLastN(\"tags\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last n tags from the 'tags' array field\n * arrayLastN(\"tags\", field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last 3 elements from an array expression\n * arrayLastN(field(\"tags\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last `n` elements of an array.\n *\n * @example\n * ```typescript\n * // Get the last n elements from an array expression\n * arrayLastN(field(\"tags\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the last `n` elements.\n */\nexport function arrayLastN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayLastN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayLastN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the maximum value in an array.\n *\n * @example\n * ```typescript\n * // Get the maximum value from the 'scores' array field\n * arrayMaximum(\"scores\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the maximum value.\n */\nexport function arrayMaximum(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the maximum value in an array.\n *\n * @example\n * ```typescript\n * // Get the maximum value from the 'scores' array field\n * arrayMaximum(field(\"scores\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the maximum value.\n */\nexport function arrayMaximum(arrayExpression: Expression): FunctionExpression;\nexport function arrayMaximum(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayMaximum();\n}\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top 3 scores from the 'scores' array field\n * arrayMaximumN(\"scores\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top n scores from the 'scores' array field\n * arrayMaximumN(\"scores\", field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top 3 elements from an array expression\n * arrayMaximumN(field(\"scores\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the largest `n` elements of an array.\n *\n * Note: Returns the n largest non-null elements in the array, in descending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the top n elements from an array expression\n * arrayMaximumN(field(\"scores\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the largest `n` elements.\n */\nexport function arrayMaximumN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayMaximumN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayMaximumN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the minimum value in an array.\n *\n * @example\n * ```typescript\n * // Get the minimum value from the 'scores' array field\n * arrayMinimum(\"scores\");\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the minimum value.\n */\nexport function arrayMinimum(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the minimum value in an array.\n *\n * @example\n * ```typescript\n * // Get the minimum value from the 'scores' array field\n * arrayMinimum(field(\"scores\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the minimum value.\n */\nexport function arrayMinimum(arrayExpression: Expression): FunctionExpression;\nexport function arrayMinimum(array: Expression | string): FunctionExpression {\n  return fieldOrExpression(array).arrayMinimum();\n}\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom 3 scores from the 'scores' array field\n * arrayMinimumN(\"scores\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(fieldName: string, n: number): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom n scores from the 'scores' array field\n * arrayMinimumN(field(\"scores\"), field(\"count\"));\n * ```\n *\n * @param fieldName - The name of the field containing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(\n  fieldName: string,\n  n: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom 3 scores from the 'scores' array field\n * arrayMinimumN(field(\"scores\"), 3);\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - The number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(\n  arrayExpression: Expression,\n  n: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the smallest `n` elements of an array.\n *\n * Note: Returns the n smallest non-null elements in the array, in ascending\n * order. This does not use a stable sort, meaning the order of equivalent\n * elements is undefined.\n *\n * @example\n * ```typescript\n * // Get the bottom n scores from the 'scores' array field\n * arrayMinimumN(field(\"scores\"), field(\"count\"));\n * ```\n *\n * @param arrayExpression - The expression representing the array.\n * @param n - An expression evaluating to the number of elements to return.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the smallest `n` elements.\n */\nexport function arrayMinimumN(\n  arrayExpression: Expression,\n  n: Expression\n): FunctionExpression;\nexport function arrayMinimumN(\n  array: Expression | string,\n  n: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(array).arrayMinimumN(valueToDefaultExpr(n));\n}\n\n/**\n *\n * Creates an expression that returns the first index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the index of \"politics\" in the 'tags' array field\n * arrayIndexOf(\"tags\", \"politics\");\n * ```\n *\n * @param fieldName - The name of the field containing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayIndexOf(\n  fieldName: string,\n  search: unknown | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the index of \"politics\" in the 'tags' array field\n * arrayIndexOf(field(\"tags\"), \"politics\");\n * ```\n *\n * @param arrayExpression - The expression representing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayIndexOf(\n  arrayExpression: Expression,\n  search: unknown | Expression\n): FunctionExpression;\nexport function arrayIndexOf(\n  array: Expression | string,\n  search: unknown | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayIndexOf(valueToDefaultExpr(search));\n}\n\n/**\n *\n * Creates an expression that returns the last index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the last index of \"politics\" in the 'tags' array field\n * arrayLastIndexOf(\"tags\", \"politics\");\n * ```\n *\n * @param fieldName - The name of the field containing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayLastIndexOf(\n  fieldName: string,\n  search: unknown | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the last index of the search value in an array.\n * Returns -1 if the value is not found.\n *\n * @example\n * ```typescript\n * // Get the last index of \"politics\" in the 'tags' array field\n * arrayLastIndexOf(field(\"tags\"), \"politics\");\n * ```\n *\n * @param arrayExpression - The expression representing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index.\n */\nexport function arrayLastIndexOf(\n  arrayExpression: Expression,\n  search: unknown | Expression\n): FunctionExpression;\nexport function arrayLastIndexOf(\n  array: Expression | string,\n  search: unknown | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayLastIndexOf(valueToDefaultExpr(search));\n}\n\n/**\n *\n * Creates an expression that returns all indices of the search value in an array.\n *\n * @example\n * ```typescript\n * // Get all indices of 5 in the 'scores' array field\n * arrayIndexOfAll(\"scores\", 5);\n * ```\n *\n * @param fieldName - The name of the field containing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the indices.\n */\nexport function arrayIndexOfAll(\n  fieldName: string,\n  search: unknown | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns all indices of the search value in an array.\n *\n * @example\n * ```typescript\n * // Get all indices of 5 in the 'scores' array field\n * arrayIndexOfAll(field(\"scores\"), 5);\n * ```\n *\n * @param arrayExpression - The expression representing the array to search.\n * @param search - The value to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the indices.\n */\nexport function arrayIndexOfAll(\n  arrayExpression: Expression,\n  search: unknown | Expression\n): FunctionExpression;\nexport function arrayIndexOfAll(\n  array: Expression | string,\n  search: unknown | Expression\n): FunctionExpression {\n  return fieldOrExpression(array).arrayIndexOfAll(valueToDefaultExpr(search));\n}\n\n/**\n *\n * Creates an expression that returns the first substring of a string field that matches a\n * specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract the domain name from an email field\n * regexFind(\"email\", \"@[A-Za-z0-9.-]+\");\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  fieldName: string,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first substring of a string field that matches a\n * specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract a substring from 'email' based on a pattern stored in another field\n * regexFind(\"email\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  fieldName: string,\n  pattern: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first substring of a string expression that matches\n * a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract the domain from a lower-cased email address\n * regexFind(field(\"email\"), \"@[A-Za-z0-9.-]+\");\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  stringExpression: Expression,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that returns the first substring of a string expression that matches\n * a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract a substring based on a dynamic pattern field\n * regexFind(field(\"email\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function.\n */\nexport function regexFind(\n  stringExpression: Expression,\n  pattern: Expression\n): FunctionExpression;\nexport function regexFind(\n  left: Expression | string,\n  pattern: Expression | string\n): FunctionExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexFind(patternExpr);\n}\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string field that\n * match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all hashtags from a post content field\n * regexFindAll(\"content\", \"#[A-Za-z0-9_]+\");\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  fieldName: string,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string field that\n * match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all matches from 'content' based on a pattern stored in another field\n * regexFindAll(\"content\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  fieldName: string,\n  pattern: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string expression\n * that match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all mentions from a lower-cased comment\n * regexFindAll(field(\"comment\"), \"@[A-Za-z0-9_]+\");\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  stringExpression: Expression,\n  pattern: string\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that evaluates to a list of all substrings in a string expression\n * that match a specified regular expression.\n *\n * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax.\n *\n * @example\n * ```typescript\n * // Extract all matches based on a dynamic pattern expression\n * regexFindAll(field(\"comment\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to search.\n * @param pattern - The regular expression to search for.\n * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings.\n */\nexport function regexFindAll(\n  stringExpression: Expression,\n  pattern: Expression\n): FunctionExpression;\nexport function regexFindAll(\n  left: Expression | string,\n  pattern: Expression | string\n): FunctionExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexFindAll(patternExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a string field matches a specified regular expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(\"email\", \"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  fieldName: string,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string field matches a specified regular expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(\"email\", field(\"pattern\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  fieldName: string,\n  pattern: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression matches a specified regular\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(field(\"email\"), \"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}\");\n * ```\n *\n * @param stringExpression - The expression representing the string to match against.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  stringExpression: Expression,\n  pattern: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression matches a specified regular\n * expression.\n *\n * @example\n * ```typescript\n * // Check if the 'email' field matches a valid email pattern\n * regexMatch(field(\"email\"), field(\"pattern\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to match against.\n * @param pattern - The regular expression to use for the match.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match.\n */\nexport function regexMatch(\n  stringExpression: Expression,\n  pattern: Expression\n): BooleanExpression;\nexport function regexMatch(\n  left: Expression | string,\n  pattern: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const patternExpr = valueToDefaultExpr(pattern);\n  return leftExpr.regexMatch(patternExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a string field contains a specified substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\".\n * stringContains(\"description\", \"example\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param substring - The substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  fieldName: string,\n  substring: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string field contains a substring specified by an expression.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains the value of the 'keyword' field.\n * stringContains(\"description\", field(\"keyword\"));\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @param substring - The expression representing the substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  fieldName: string,\n  substring: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a specified substring.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains \"example\".\n * stringContains(field(\"description\"), \"example\");\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param substring - The substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  stringExpression: Expression,\n  substring: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression contains a substring specified by another expression.\n *\n * @example\n * ```typescript\n * // Check if the 'description' field contains the value of the 'keyword' field.\n * stringContains(field(\"description\"), field(\"keyword\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to perform the comparison on.\n * @param substring - The expression representing the substring to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison.\n */\nexport function stringContains(\n  stringExpression: Expression,\n  substring: Expression\n): BooleanExpression;\nexport function stringContains(\n  left: Expression | string,\n  substring: Expression | string\n): BooleanExpression {\n  const leftExpr = fieldOrExpression(left);\n  const substringExpr = valueToDefaultExpr(substring);\n  return leftExpr.stringContains(substringExpr);\n}\n\n/**\n *\n * Creates an expression that checks if a field's value starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the 'name' field starts with \"Mr.\"\n * startsWith(\"name\", \"Mr.\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @param prefix - The prefix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  fieldName: string,\n  prefix: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the 'fullName' field starts with the value of the 'firstName' field\n * startsWith(\"fullName\", field(\"firstName\"));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param prefix - The expression representing the prefix.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  fieldName: string,\n  prefix: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with \"Mr.\"\n * startsWith(field(\"fullName\"), \"Mr.\");\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param prefix - The prefix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  stringExpression: Expression,\n  prefix: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression starts with a given prefix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with \"Mr.\"\n * startsWith(field(\"fullName\"), field(\"prefix\"));\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param prefix - The prefix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison.\n */\nexport function startsWith(\n  stringExpression: Expression,\n  prefix: Expression\n): BooleanExpression;\nexport function startsWith(\n  expr: Expression | string,\n  prefix: Expression | string\n): BooleanExpression {\n  return fieldOrExpression(expr).startsWith(valueToDefaultExpr(prefix));\n}\n\n/**\n *\n * Creates an expression that checks if a field's value ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the 'filename' field ends with \".txt\"\n * endsWith(\"filename\", \".txt\");\n * ```\n *\n * @param fieldName - The field name to check.\n * @param suffix - The postfix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(fieldName: string, suffix: string): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a field's value ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the 'url' field ends with the value of the 'extension' field\n * endsWith(\"url\", field(\"extension\"));\n * ```\n *\n * @param fieldName - The field name to check.\n * @param suffix - The expression representing the postfix.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(\n  fieldName: string,\n  suffix: Expression\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with \"Jr.\"\n * endsWith(field(\"fullName\"), \"Jr.\");\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param suffix - The postfix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(\n  stringExpression: Expression,\n  suffix: string\n): BooleanExpression;\n\n/**\n *\n * Creates an expression that checks if a string expression ends with a given postfix.\n *\n * @example\n * ```typescript\n * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with \"Jr.\"\n * endsWith(field(\"fullName\"), constant(\"Jr.\"));\n * ```\n *\n * @param stringExpression - The expression to check.\n * @param suffix - The postfix to check for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison.\n */\nexport function endsWith(\n  stringExpression: Expression,\n  suffix: Expression\n): BooleanExpression;\nexport function endsWith(\n  expr: Expression | string,\n  suffix: Expression | string\n): BooleanExpression {\n  return fieldOrExpression(expr).endsWith(valueToDefaultExpr(suffix));\n}\n\n/**\n *\n * Creates an expression that converts a string field to lowercase.\n *\n * @example\n * ```typescript\n * // Convert the 'name' field to lowercase\n * toLower(\"name\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the lowercase string.\n */\nexport function toLower(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a string expression to lowercase.\n *\n * @example\n * ```typescript\n * // Convert the 'name' field to lowercase\n * toLower(field(\"name\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to convert to lowercase.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the lowercase string.\n */\nexport function toLower(stringExpression: Expression): FunctionExpression;\nexport function toLower(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).toLower();\n}\n\n/**\n *\n * Creates an expression that converts a string field to uppercase.\n *\n * @example\n * ```typescript\n * // Convert the 'title' field to uppercase\n * toUpper(\"title\");\n * ```\n *\n * @param fieldName - The name of the field containing the string.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the uppercase string.\n */\nexport function toUpper(fieldName: string): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a string expression to uppercase.\n *\n * @example\n * ```typescript\n * // Convert the 'title' field to uppercase\n * toUpper(field(\"title\"));\n * ```\n *\n * @param stringExpression - The expression representing the string to convert to uppercase.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the uppercase string.\n */\nexport function toUpper(stringExpression: Expression): FunctionExpression;\nexport function toUpper(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).toUpper();\n}\n\n/**\n *\n * Creates an expression that removes leading and trailing whitespace from a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the 'userInput' field\n * trim(\"userInput\");\n *\n * // Trim quotes from the 'userInput' field\n * trim(\"userInput\", '\"');\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be\n * trimmed from the input. If not specified, then whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string.\n */\nexport function trim(\n  fieldName: string,\n  valueToTrim?: string | Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that removes leading and trailing characters from a string or byte array expression.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the 'userInput' field\n * trim(field(\"userInput\"));\n *\n * // Trim quotes from the 'userInput' field\n * trim(field(\"userInput\"), '\"');\n * ```\n *\n * @param stringExpression - The expression representing the string or byte array to trim.\n * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be\n * trimmed from the input. If not specified, then whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function trim(\n  stringExpression: Expression,\n  valueToTrim?: string | Expression\n): FunctionExpression;\nexport function trim(\n  expr: Expression | string,\n  valueToTrim?: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(expr).trim(valueToTrim);\n}\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"));\n *\n * // Trim quotes from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function ltrim(\n  fieldName: string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"));\n *\n * // Trim quotes from the beginning of the 'userInput' field\n * ltrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function ltrim(\n  expression: Expression,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\nexport function ltrim(\n  expr: Expression | string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).ltrim(valueToTrim);\n}\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the end of the 'userInput' field\n * rtrim(field(\"userInput\"));\n *\n * // Trim quotes from the end of the 'userInput' field\n * rtrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function rtrim(\n  fieldName: string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.\n *\n * @example\n * ```typescript\n * // Trim whitespace from the end of the 'userInput' field\n * rtrim(field(\"userInput\"));\n *\n * // Trim quotes from the end of the 'userInput' field\n * rtrim(field(\"userInput\"), '\"');\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.\n * If not specified, whitespace will be trimmed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array.\n */\nexport function rtrim(\n  expression: Expression,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression;\nexport function rtrim(\n  expr: Expression | string,\n  valueToTrim?: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).rtrim(valueToTrim);\n}\n\n/**\n * Creates an expression that returns the data type of the data in the specified field.\n *\n * @remarks\n * String inputs passed iteratively to this global function act as `field()` path lookups.\n * If you wish to pass a string literal value, it must be wrapped: `type(constant(\"my_string\"))`.\n *\n * @example\n * ```typescript\n * // Get the data type of the value in field 'title'\n * type('title')\n * ```\n *\n * @returns A new `Expression` representing the data type.\n */\nexport function type(fieldName: string): FunctionExpression;\n/**\n * Creates an expression that returns the data type of an expression's result.\n *\n * @example\n * ```typescript\n * // Get the data type of a conditional expression\n * type(conditional(exists('foo'), constant(1), constant(true)))\n * ```\n *\n * @returns A new `Expression` representing the data type.\n */\nexport function type(expression: Expression): FunctionExpression;\nexport function type(\n  fieldNameOrExpression: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).type();\n}\n\n/**\n * Creates an expression that checks if the value in the specified field is of the given type.\n *\n * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.\n * Supported values for `type` are:\n * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,\n * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,\n * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.\n *\n * @example\n * ```typescript\n * // Check if the 'price' field is a floating point number (evaluating to true inside pipeline conditionals)\n * isType('price', 'float64');\n * ```\n *\n * @param fieldName - The name of the field to check.\n * @param type - The type to check for.\n * @returns A new `BooleanExpression` that evaluates to true if the field's value is of the given type, false otherwise.\n */\nexport function isType(fieldName: string, type: string): BooleanExpression;\n\n/**\n * Creates an expression that checks if the result of an expression is of the given type.\n *\n * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.\n * Supported values for `type` are:\n * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,\n * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,\n * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.\n *\n * @example\n * ```typescript\n * // Check if the result of a calculation is a number\n * isType(add('count', 1), 'number')\n * ```\n *\n * @param expression - The expression to check.\n * @param type - The type to check for.\n * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise.\n */\nexport function isType(expression: Expression, type: string): BooleanExpression;\nexport function isType(\n  fieldNameOrExpression: string | Expression,\n  type: string\n): BooleanExpression {\n  return fieldOrExpression(fieldNameOrExpression).isType(type);\n}\n\n/**\n *\n * Creates an expression that concatenates string functions, fields or constants together.\n *\n * @example\n * ```typescript\n * // Combine the 'firstName', \" \", and 'lastName' fields into a single string\n * stringConcat(\"firstName\", \" \", field(\"lastName\"));\n * ```\n *\n * @param fieldName - The field name containing the initial string value.\n * @param secondString - An expression or string literal to concatenate.\n * @param otherStrings - Optional additional expressions or literals (typically strings) to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated string.\n */\nexport function stringConcat(\n  fieldName: string,\n  secondString: Expression | string,\n  ...otherStrings: Array<Expression | string>\n): FunctionExpression;\n\n/**\n * Creates an expression that concatenates string expressions together.\n *\n * @example\n * ```typescript\n * // Combine the 'firstName', \" \", and 'lastName' fields into a single string\n * stringConcat(field(\"firstName\"), \" \", field(\"lastName\"));\n * ```\n *\n * @param firstString - The initial string expression to concatenate to.\n * @param secondString - An expression or string literal to concatenate.\n * @param otherStrings - Optional additional expressions or literals (typically strings) to concatenate.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated string.\n */\nexport function stringConcat(\n  firstString: Expression,\n  secondString: Expression | string,\n  ...otherStrings: Array<Expression | string>\n): FunctionExpression;\nexport function stringConcat(\n  first: string | Expression,\n  second: string | Expression,\n  ...elements: Array<string | Expression>\n): FunctionExpression {\n  return fieldOrExpression(first).stringConcat(\n    valueToDefaultExpr(second),\n    ...elements.map(valueToDefaultExpr)\n  );\n}\n\n/**\n * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.\n *\n * @example\n * ```typescript\n * // Find the index of \"foo\" in the 'text' field\n * stringIndexOf(\"text\", \"foo\");\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param search - The substring or byte sequence to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index of the first occurrence.\n */\nexport function stringIndexOf(\n  fieldName: string,\n  search: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.\n *\n * @example\n * ```typescript\n * // Find the index of \"foo\" in the 'text' field\n * stringIndexOf(field(\"text\"), \"foo\");\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param search - The substring or byte sequence to search for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index of the first occurrence.\n */\nexport function stringIndexOf(\n  expression: Expression,\n  search: string | Expression | Bytes\n): FunctionExpression;\nexport function stringIndexOf(\n  expr: Expression | string,\n  search: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).stringIndexOf(search);\n}\n\n/**\n * Creates an expression that repeats a string or byte array a specified number of times.\n *\n * @example\n * ```typescript\n * // Repeat the 'label' field 3 times\n * stringRepeat(\"label\", 3);\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param repetitions - The number of times to repeat the string or byte array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the repeated string or byte array.\n */\nexport function stringRepeat(\n  fieldName: string,\n  repetitions: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that repeats a string or byte array a specified number of times.\n *\n * @example\n * ```typescript\n * // Repeat the 'label' field 3 times\n * stringRepeat(field(\"label\"), 3);\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param repetitions - The number of times to repeat the string or byte array.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the repeated string or byte array.\n */\nexport function stringRepeat(\n  expression: Expression,\n  repetitions: number | Expression\n): FunctionExpression;\nexport function stringRepeat(\n  expr: Expression | string,\n  repetitions: number | Expression\n): FunctionExpression {\n  return fieldOrExpression(expr).stringRepeat(repetitions);\n}\n\n/**\n * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace all occurrences of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceAll(\"text\", \"foo\", \"bar\");\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with replacements.\n */\nexport function stringReplaceAll(\n  fieldName: string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace all occurrences of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceAll(field(\"text\"), \"foo\", \"bar\");\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with replacements.\n */\nexport function stringReplaceAll(\n  expression: Expression,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\nexport function stringReplaceAll(\n  expr: Expression | string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).stringReplaceAll(find, replacement);\n}\n\n/**\n * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace the first occurrence of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceOne(\"text\", \"foo\", \"bar\");\n * ```\n *\n * @param fieldName - The name of the field containing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with the replacement.\n */\nexport function stringReplaceOne(\n  fieldName: string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\n\n/**\n * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.\n *\n * @example\n * ```typescript\n * // Replace the first occurrence of \"foo\" with \"bar\" in the 'text' field\n * stringReplaceOne(field(\"text\"), \"foo\", \"bar\");\n * ```\n *\n * @param expression - The expression representing the string or byte array.\n * @param find - The substring or byte sequence to search for.\n * @param replacement - The replacement string or byte sequence.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with the replacement.\n */\nexport function stringReplaceOne(\n  expression: Expression,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression;\nexport function stringReplaceOne(\n  expr: Expression | string,\n  find: string | Expression | Bytes,\n  replacement: string | Expression | Bytes\n): FunctionExpression {\n  return fieldOrExpression(expr).stringReplaceOne(find, replacement);\n}\n\n/**\n *\n * Accesses a value from a map (object) field using the provided key.\n *\n * @example\n * ```typescript\n * // Get the 'city' value from the 'address' map field\n * mapGet(\"address\", \"city\");\n * ```\n *\n * @param fieldName - The field name of the map field.\n * @param subField - The key to access in the map.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the value associated with the given key in the map.\n */\nexport function mapGet(fieldName: string, subField: string): FunctionExpression;\n\n/**\n *\n * Accesses a value from a map (object) expression using the provided key.\n *\n * @example\n * ```typescript\n * // Get the 'city' value from the 'address' map field\n * mapGet(field(\"address\"), \"city\");\n * ```\n *\n * @param mapExpression - The expression representing the map.\n * @param subField - The key to access in the map.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the value associated with the given key in the map.\n */\nexport function mapGet(\n  mapExpression: Expression,\n  subField: string\n): FunctionExpression;\nexport function mapGet(\n  fieldOrExpr: string | Expression,\n  subField: string\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapGet(subField);\n}\n\n/**\n * Creates an expression that returns a new map with the specified entries added or updated.\n *\n * @remarks\n * This only performs shallow updates to the map. Setting a value to `null`\n * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.\n *\n * @example\n * ```typescript\n * // Set the 'city' to 'San Francisco' in the 'address' map field\n * mapSet(\"address\", \"city\", \"San Francisco\");\n * ```\n *\n * @param mapField - The map field to set entries in.\n * @param key - The key to set. Must be a string or a constant string expression.\n * @param value - The value to set.\n * @param moreKeyValues - Additional key-value pairs to set.\n * @returns A new `Expression` representing the map with the entries set.\n */\nexport function mapSet(\n  mapField: string,\n  key: string | Expression,\n  value: unknown,\n  ...moreKeyValues: unknown[]\n): FunctionExpression;\n\n/**\n * Creates an expression that returns a new map with the specified entries added or updated.\n *\n * @remarks\n * This only performs shallow updates to the map. Setting a value to `null`\n * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.\n *\n * @example\n * ```typescript\n * // Set the 'city' to \"San Francisco\"\n * mapSet(map({\"state\": \"California\"}), \"city\", \"San Francisco\");\n * ```\n *\n * @param mapExpression - The expression representing the map.\n * @param key - The key to set. Must be a string or a constant string expression.\n * @param value - The value to set.\n * @param moreKeyValues - Additional key-value pairs to set.\n * @returns A new `Expression` representing the map with the entries set.\n */\nexport function mapSet(\n  mapExpression: Expression,\n  key: string | Expression,\n  value: unknown,\n  ...moreKeyValues: unknown[]\n): FunctionExpression;\nexport function mapSet(\n  fieldOrExpr: string | Expression,\n  key: string | Expression,\n  value: unknown,\n  ...moreKeyValues: unknown[]\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapSet(key, value, ...moreKeyValues);\n}\n\n/**\n * Creates an expression that returns the keys of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the keys of the 'address' map field\n * mapKeys(\"address\");\n * ```\n *\n * @param mapField - The map field to get the keys of.\n * @returns A new `Expression` representing the keys of the map.\n */\nexport function mapKeys(mapField: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the keys of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the keys of the map expression\n * mapKeys(map({\"city\": \"San Francisco\"}));\n * ```\n *\n * @param mapExpression - The expression representing the map to get the keys of.\n * @returns A new `Expression` representing the keys of the map.\n */\nexport function mapKeys(mapExpression: Expression): FunctionExpression;\nexport function mapKeys(fieldOrExpr: string | Expression): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapKeys();\n}\n\n/**\n * Creates an expression that returns the values of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the values of the 'address' map field\n * mapValues(\"address\");\n * ```\n *\n * @param mapField - The map field to get the values of.\n * @returns A new `Expression` representing the values of the map.\n */\nexport function mapValues(mapField: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the values of a map.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the values of the map expression\n * mapValues(map({\"city\": \"San Francisco\"}));\n * ```\n *\n * @param mapExpression - The expression representing the map to get the values of.\n * @returns A new `Expression` representing the values of the map.\n */\nexport function mapValues(mapExpression: Expression): FunctionExpression;\nexport function mapValues(\n  fieldOrExpr: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapValues();\n}\n\n/**\n * Creates an expression that returns the entries of a map as an array of maps,\n * where each map contains a `\"k\"` property for the key and a `\"v\"` property for the value.\n * For example: `[{ k: \"key1\", v: \"value1\" }, ...]`.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the entries of the 'address' map field\n * mapEntries(\"address\");\n * ```\n *\n * @param mapField - The map field to get the entries of.\n * @returns A new `Expression` representing the entries of the map.\n */\nexport function mapEntries(mapField: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the entries of a map as an array of maps,\n * where each map contains a `\"k\"` property for the key and a `\"v\"` property for the value.\n * For example: `[{ k: \"key1\", v: \"value1\" }, ...]`.\n *\n * @remarks\n * While the backend generally preserves insertion order, relying on the\n * order of the output array is not guaranteed and should be avoided.\n *\n * @example\n * ```typescript\n * // Get the entries of the map expression\n * mapEntries(map({\"city\": \"San Francisco\"}));\n * ```\n *\n * @param mapExpression - The expression representing the map to get the entries of.\n * @returns A new `Expression` representing the entries of the map.\n */\nexport function mapEntries(mapExpression: Expression): FunctionExpression;\nexport function mapEntries(\n  fieldOrExpr: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldOrExpr).mapEntries();\n}\n\n/**\n * @public\n * Creates an expression that returns the value of a field from a document that results from the evaluation of the expression.\n *\n * @example\n * ```typescript\n * // Get the value of the \"city\" field in the \"address\" document.\n * getField(field(\"address\"), \"city\")\n * ```\n *\n * @param key The field to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(expression: Expression, key: string): Expression;\n/**\n * @public\n * Creates an expression that returns the value of a field from a document that results from the evaluation of the expression.\n *\n * @example\n * ```typescript\n * // Get the value of the key resulting from the \"addressField\" variable in the \"address\" document.\n * getField(field(\"address\", variable(\"addressField\")),\n * ```\n *\n * @param key The expression representing the key to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(\n  expression: Expression,\n  keyExpr: Expression\n): Expression;\n/**\n * @public\n * Creates an expression that returns the value of a field from the document with the given field name.\n *\n * @example\n * ```typescript\n * // Get the value of the \"city\" field in the \"address\" document.\n * getField(\"address\", \"city\")\n * ```\n *\n * @param key The field to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(fieldName: string, key: string): Expression;\n/**\n * @public\n * Creates an expression that returns the value of a field from the document with the given field name.\n *\n * @example\n * ```typescript\n * // Get the value of the \"city\" field in the \"address\" document.\n * getField(\"address\", variable(\"addressField\"))\n * ```\n *\n * @param key The field to access in the document.\n * @returns A new `Expression` representing the value of the field in the document.\n */\nexport function getField(fieldName: string, keyExpr: Expression): Expression;\nexport function getField(\n  fieldOrExpr: string | Expression,\n  keyOrExpr: string | Expression\n): Expression {\n  return fieldOrExpression(fieldOrExpr).getField(keyOrExpr);\n}\n\n/**\n * Creates an aggregation that counts the total number of stage inputs.\n *\n * @example\n * ```typescript\n * // Count the total number of input documents\n * countAll().as(\"totalDocument\");\n * ```\n *\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'countAll' aggregation.\n */\nexport function countAll(): AggregateFunction {\n  return AggregateFunction._create('count', [], 'count');\n}\n\n/**\n *\n * Creates an aggregation that counts the number of stage inputs with valid evaluations of the\n * provided expression.\n *\n * @example\n * ```typescript\n * // Count the number of items where the price is greater than 10\n * count(field(\"price\").greaterThan(10)).as(\"expensiveItemCount\");\n * ```\n *\n * @param expression - The expression to count.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'count' aggregation.\n */\nexport function count(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that counts the number of stage inputs where the input field exists.\n *\n * @example\n * ```typescript\n * // Count the total number of products\n * count(\"productId\").as(\"totalProducts\");\n * ```\n *\n * @param fieldName - The name of the field to count.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'count' aggregation.\n */\nexport function count(fieldName: string): AggregateFunction;\nexport function count(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).count();\n}\n\n/**\n *\n * Creates an aggregation that calculates the sum of values from an expression across multiple\n * stage inputs.\n *\n * @example\n * ```typescript\n * // Calculate the total revenue from a set of orders\n * sum(field(\"orderAmount\")).as(\"totalRevenue\");\n * ```\n *\n * @param expression - The expression to sum up.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'sum' aggregation.\n */\nexport function sum(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that calculates the sum of a field's values across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Calculate the total revenue from a set of orders\n * sum(\"orderAmount\").as(\"totalRevenue\");\n * ```\n *\n * @param fieldName - The name of the field containing numeric values to sum up.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'sum' aggregation.\n */\nexport function sum(fieldName: string): AggregateFunction;\nexport function sum(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).sum();\n}\n\n/**\n *\n * Creates an aggregation that calculates the average (mean) of values from an expression across\n * multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Calculate the average age of users\n * average(field(\"age\")).as(\"averageAge\");\n * ```\n *\n * @param expression - The expression representing the values to average.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'average' aggregation.\n */\nexport function average(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that calculates the average (mean) of a field's values across multiple\n * stage inputs.\n *\n * @example\n * ```typescript\n * // Calculate the average age of users\n * average(\"age\").as(\"averageAge\");\n * ```\n *\n * @param fieldName - The name of the field containing numeric values to average.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'average' aggregation.\n */\nexport function average(fieldName: string): AggregateFunction;\nexport function average(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).average();\n}\n\n/**\n *\n * Creates an aggregation that finds the minimum value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the lowest price of all products\n * minimum(field(\"price\")).as(\"lowestPrice\");\n * ```\n *\n * @param expression - The expression to find the minimum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'minimum' aggregation.\n */\nexport function minimum(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that finds the minimum value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the lowest price of all products\n * minimum(\"price\").as(\"lowestPrice\");\n * ```\n *\n * @param fieldName - The name of the field to find the minimum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'minimum' aggregation.\n */\nexport function minimum(fieldName: string): AggregateFunction;\nexport function minimum(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).minimum();\n}\n\n/**\n *\n * Creates an aggregation that finds the maximum value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the highest score in a leaderboard\n * maximum(field(\"score\")).as(\"highestScore\");\n * ```\n *\n * @param expression - The expression to find the maximum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'maximum' aggregation.\n */\nexport function maximum(expression: Expression): AggregateFunction;\n\n/**\n *\n * Creates an aggregation that finds the maximum value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the highest score in a leaderboard\n * maximum(\"score\").as(\"highestScore\");\n * ```\n *\n * @param fieldName - The name of the field to find the maximum value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'maximum' aggregation.\n */\nexport function maximum(fieldName: string): AggregateFunction;\nexport function maximum(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).maximum();\n}\n\n/**\n * Creates an aggregation that finds the first value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the first value of the 'rating' field\n * first(field(\"rating\")).as(\"firstRating\");\n * ```\n *\n * @param expression - The expression to find the first value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'first' aggregation.\n */\nexport function first(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that finds the first value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the first value of the 'rating' field\n * first(\"rating\").as(\"firstRating\");\n * ```\n *\n * @param fieldName - The name of the field to find the first value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'first' aggregation.\n */\nexport function first(fieldName: string): AggregateFunction;\nexport function first(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).first();\n}\n\n/**\n * Creates an aggregation that finds the last value of an expression across multiple stage\n * inputs.\n *\n * @example\n * ```typescript\n * // Find the last value of the 'rating' field\n * last(field(\"rating\")).as(\"lastRating\");\n * ```\n *\n * @param expression - The expression to find the last value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'last' aggregation.\n */\nexport function last(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that finds the last value of a field across multiple stage inputs.\n *\n * @example\n * ```typescript\n * // Find the last value of the 'rating' field\n * last(\"rating\").as(\"lastRating\");\n * ```\n *\n * @param fieldName - The name of the field to find the last value of.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'last' aggregation.\n */\nexport function last(fieldName: string): AggregateFunction;\nexport function last(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).last();\n}\n\n/**\n * Creates an aggregation that collects all values of an expression across multiple stage\n * inputs into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all tags from books into an array\n * arrayAgg(field(\"tags\")).as(\"allTags\");\n * ```\n *\n * @param expression - The expression to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg' aggregation.\n */\nexport function arrayAgg(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that collects all values of a field across multiple stage inputs\n * into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all tags from books into an array\n * arrayAgg(\"tags\").as(\"allTags\");\n * ```\n *\n * @param fieldName - The name of the field to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg' aggregation.\n */\nexport function arrayAgg(fieldName: string): AggregateFunction;\nexport function arrayAgg(value: Expression | string): AggregateFunction {\n  return fieldOrExpression(value).arrayAgg();\n}\n\n/**\n * Creates an aggregation that collects all distinct values of an expression across multiple stage\n * inputs into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all distinct tags from books into an array\n * arrayAggDistinct(field(\"tags\")).as(\"allDistinctTags\");\n * ```\n *\n * @param expression - The expression to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg_distinct' aggregation.\n */\nexport function arrayAggDistinct(expression: Expression): AggregateFunction;\n\n/**\n * Creates an aggregation that collects all distinct values of a field across multiple stage inputs\n * into an array.\n *\n * @remarks\n * If the expression resolves to an absent value, it is converted to `null`.\n * The order of elements in the output array is not stable and shouldn't be relied upon.\n *\n * @example\n * ```typescript\n * // Collect all distinct tags from books into an array\n * arrayAggDistinct(\"tags\").as(\"allDistinctTags\");\n * ```\n *\n * @param fieldName - The name of the field to collect values from.\n * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg_distinct' aggregation.\n */\nexport function arrayAggDistinct(fieldName: string): AggregateFunction;\nexport function arrayAggDistinct(\n  value: Expression | string\n): AggregateFunction {\n  return fieldOrExpression(value).arrayAggDistinct();\n}\n\n/**\n *\n * Calculates the Cosine distance between a field's vector value and a literal vector value.\n *\n * @example\n * ```typescript\n * // Calculate the Cosine distance between the 'location' field and a target location\n * cosineDistance(\"location\", [37.7749, -122.4194]);\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vector - The other vector (as an array of doubles) or {@link VectorValue} to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  fieldName: string,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Cosine distance between a field's vector value and a vector expression.\n *\n * @example\n * ```typescript\n * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field\n * cosineDistance(\"userVector\", field(\"itemVector\"));\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  fieldName: string,\n  vectorExpression: Expression\n): FunctionExpression;\n\n/**\n *\n * Calculates the Cosine distance between a vector expression and a vector literal.\n *\n * @example\n * ```typescript\n * // Calculate the cosine distance between the 'location' field and a target location\n * cosineDistance(field(\"location\"), [37.7749, -122.4194]);\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param vector - The other vector (as an array of doubles or VectorValue) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  vectorExpression: Expression,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Cosine distance between two vector expressions.\n *\n * @example\n * ```typescript\n * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field\n * cosineDistance(field(\"userVector\"), field(\"itemVector\"));\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param otherVectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors.\n */\nexport function cosineDistance(\n  vectorExpression: Expression,\n  otherVectorExpression: Expression\n): FunctionExpression;\nexport function cosineDistance(\n  expr: Expression | string,\n  other: Expression | number[] | VectorValue\n): FunctionExpression {\n  const expr1 = fieldOrExpression(expr);\n  const expr2 = vectorToExpr(other);\n  return expr1.cosineDistance(expr2);\n}\n\n/**\n *\n * Calculates the dot product between a field's vector value and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the dot product distance between a feature vector and a target vector\n * dotProduct(\"features\", [0.5, 0.8, 0.2]);\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vector - The other vector (as an array of doubles or VectorValue) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  fieldName: string,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the dot product between a field's vector value and a vector expression.\n *\n * @example\n * ```typescript\n * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2'\n * dotProduct(\"docVector1\", field(\"docVector2\"));\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vectorExpression - The other vector (represented as an `Expression`) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  fieldName: string,\n  vectorExpression: Expression\n): FunctionExpression;\n\n/**\n *\n * Calculates the dot product between a vector expression and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the dot product between a feature vector and a target vector\n * dotProduct(field(\"features\"), [0.5, 0.8, 0.2]);\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to calculate with.\n * @param vector - The other vector (as an array of doubles or VectorValue) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  vectorExpression: Expression,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the dot product between two vector expressions.\n *\n * @example\n * ```typescript\n * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2'\n * dotProduct(field(\"docVector1\"), field(\"docVector2\"));\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to calculate with.\n * @param otherVectorExpression - The other vector (represented as an `Expression`) to calculate with.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors.\n */\nexport function dotProduct(\n  vectorExpression: Expression,\n  otherVectorExpression: Expression\n): FunctionExpression;\nexport function dotProduct(\n  expr: Expression | string,\n  other: Expression | number[] | VectorValue\n): FunctionExpression {\n  const expr1 = fieldOrExpression(expr);\n  const expr2 = vectorToExpr(other);\n  return expr1.dotProduct(expr2);\n}\n\n/**\n *\n * Calculates the Euclidean distance between a field's vector value and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between the 'location' field and a target location\n * euclideanDistance(\"location\", [37.7749, -122.4194]);\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vector - The other vector (as an array of doubles or VectorValue) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  fieldName: string,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Euclidean distance between a field's vector value and a vector expression.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB'\n * euclideanDistance(\"pointA\", field(\"pointB\"));\n * ```\n *\n * @param fieldName - The name of the field containing the first vector.\n * @param vectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  fieldName: string,\n  vectorExpression: Expression\n): FunctionExpression;\n\n/**\n *\n * Calculates the Euclidean distance between a vector expression and a double array.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between the 'location' field and a target location\n *\n * euclideanDistance(field(\"location\"), [37.7749, -122.4194]);\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param vector - The other vector (as an array of doubles or VectorValue) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  vectorExpression: Expression,\n  vector: number[] | VectorValue\n): FunctionExpression;\n\n/**\n *\n * Calculates the Euclidean distance between two vector expressions.\n *\n * @example\n * ```typescript\n * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB'\n * euclideanDistance(field(\"pointA\"), field(\"pointB\"));\n * ```\n *\n * @param vectorExpression - The first vector (represented as an `Expression`) to compare against.\n * @param otherVectorExpression - The other vector (represented as an `Expression`) to compare against.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors.\n */\nexport function euclideanDistance(\n  vectorExpression: Expression,\n  otherVectorExpression: Expression\n): FunctionExpression;\nexport function euclideanDistance(\n  expr: Expression | string,\n  other: Expression | number[] | VectorValue\n): FunctionExpression {\n  const expr1 = fieldOrExpression(expr);\n  const expr2 = vectorToExpr(other);\n  return expr1.euclideanDistance(expr2);\n}\n\n/**\n *\n * Creates an expression that calculates the length of a Firestore Vector.\n *\n * @example\n * ```typescript\n * // Get the vector length (dimension) of the field 'embedding'.\n * vectorLength(field(\"embedding\"));\n * ```\n *\n * @param vectorExpression - The expression representing the Firestore Vector.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function vectorLength(vectorExpression: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that calculates the length of a Firestore Vector represented by a field.\n *\n * @example\n * ```typescript\n * // Get the vector length (dimension) of the field 'embedding'.\n * vectorLength(\"embedding\");\n * ```\n *\n * @param fieldName - The name of the field representing the Firestore Vector.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array.\n */\nexport function vectorLength(fieldName: string): FunctionExpression;\nexport function vectorLength(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).vectorLength();\n}\n\n/**\n *\n * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'microseconds' field as microseconds since epoch.\n * unixMicrosToTimestamp(field(\"microseconds\"));\n * ```\n *\n * @param expr - The expression representing the number of microseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMicrosToTimestamp(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'microseconds' field as microseconds since epoch.\n * unixMicrosToTimestamp(\"microseconds\");\n * ```\n *\n * @param fieldName - The name of the field representing the number of microseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMicrosToTimestamp(fieldName: string): FunctionExpression;\nexport function unixMicrosToTimestamp(\n  expr: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(expr).unixMicrosToTimestamp();\n}\n\n/**\n *\n * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to microseconds since epoch.\n * timestampToUnixMicros(field(\"timestamp\"));\n * ```\n *\n * @param expr - The expression representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.\n */\nexport function timestampToUnixMicros(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to microseconds since epoch.\n * timestampToUnixMicros(\"timestamp\");\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.\n */\nexport function timestampToUnixMicros(fieldName: string): FunctionExpression;\nexport function timestampToUnixMicros(\n  expr: Expression | string\n): FunctionExpression {\n  return fieldOrExpression(expr).timestampToUnixMicros();\n}\n\n/**\n *\n * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'milliseconds' field as milliseconds since epoch.\n * unixMillisToTimestamp(field(\"milliseconds\"));\n * ```\n *\n * @param expr - The expression representing the number of milliseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMillisToTimestamp(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'milliseconds' field as milliseconds since epoch.\n * unixMillisToTimestamp(\"milliseconds\");\n * ```\n *\n * @param fieldName - The name of the field representing the number of milliseconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixMillisToTimestamp(fieldName: string): FunctionExpression;\nexport function unixMillisToTimestamp(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.unixMillisToTimestamp();\n}\n\n/**\n *\n * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to milliseconds since epoch.\n * timestampToUnixMillis(field(\"timestamp\"));\n * ```\n *\n * @param expr - The expression representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.\n */\nexport function timestampToUnixMillis(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to milliseconds since epoch.\n * timestampToUnixMillis(\"timestamp\");\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.\n */\nexport function timestampToUnixMillis(fieldName: string): FunctionExpression;\nexport function timestampToUnixMillis(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.timestampToUnixMillis();\n}\n\n/**\n *\n * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'seconds' field as seconds since epoch.\n * unixSecondsToTimestamp(field(\"seconds\"));\n * ```\n *\n * @param expr - The expression representing the number of seconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixSecondsToTimestamp(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)\n * and returns a timestamp.\n *\n * @example\n * ```typescript\n * // Interpret the 'seconds' field as seconds since epoch.\n * unixSecondsToTimestamp(\"seconds\");\n * ```\n *\n * @param fieldName - The name of the field representing the number of seconds since epoch.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.\n */\nexport function unixSecondsToTimestamp(fieldName: string): FunctionExpression;\nexport function unixSecondsToTimestamp(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.unixSecondsToTimestamp();\n}\n\n/**\n *\n * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to seconds since epoch.\n * timestampToUnixSeconds(field(\"timestamp\"));\n * ```\n *\n * @param expr - The expression representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.\n */\nexport function timestampToUnixSeconds(expr: Expression): FunctionExpression;\n\n/**\n *\n * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).\n *\n * @example\n * ```typescript\n * // Convert the 'timestamp' field to seconds since epoch.\n * timestampToUnixSeconds(\"timestamp\");\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.\n */\nexport function timestampToUnixSeconds(fieldName: string): FunctionExpression;\nexport function timestampToUnixSeconds(\n  expr: Expression | string\n): FunctionExpression {\n  const normalizedExpr = fieldOrExpression(expr);\n  return normalizedExpr.timestampToUnixSeconds();\n}\n\n/**\n *\n * Creates an expression that adds a specified amount of time to a timestamp.\n *\n * @example\n * ```typescript\n * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field.\n * timestampAdd(field(\"timestamp\"), field(\"unit\"), field(\"amount\"));\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n * @param amount - The expression evaluates to amount of the unit.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampAdd(\n  timestamp: Expression,\n  unit: Expression,\n  amount: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that adds a specified amount of time to a timestamp.\n *\n * @example\n * ```typescript\n * // Add 1 day to the 'timestamp' field.\n * timestampAdd(field(\"timestamp\"), \"day\", 1);\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The unit of time to add (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampAdd(\n  timestamp: Expression,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that adds a specified amount of time to a timestamp represented by a field.\n *\n * @example\n * ```typescript\n * // Add 1 day to the 'timestamp' field.\n * timestampAdd(\"timestamp\", \"day\", 1);\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param unit - The unit of time to add (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to add.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampAdd(\n  fieldName: string,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\nexport function timestampAdd(\n  timestamp: Expression | string,\n  unit: TimeUnit | Expression,\n  amount: Expression | number\n): FunctionExpression {\n  const normalizedTimestamp = fieldOrExpression(timestamp);\n  const normalizedUnit = valueToDefaultExpr(unit);\n  const normalizedAmount = valueToDefaultExpr(amount);\n  return normalizedTimestamp.timestampAdd(normalizedUnit, normalizedAmount);\n}\n\n/**\n *\n * Creates an expression that subtracts a specified amount of time from a timestamp.\n *\n * @example\n * ```typescript\n * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field.\n * timestampSubtract(field(\"timestamp\"), field(\"unit\"), field(\"amount\"));\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.\n * @param amount - The expression evaluates to amount of the unit.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampSubtract(\n  timestamp: Expression,\n  unit: Expression,\n  amount: Expression\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a specified amount of time from a timestamp.\n *\n * @example\n * ```typescript\n * // Subtract 1 day from the 'timestamp' field.\n * timestampSubtract(field(\"timestamp\"), \"day\", 1);\n * ```\n *\n * @param timestamp - The expression representing the timestamp.\n * @param unit - The unit of time to subtract (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampSubtract(\n  timestamp: Expression,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\n\n/**\n *\n * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field.\n *\n * @example\n * ```typescript\n * // Subtract 1 day from the 'timestamp' field.\n * timestampSubtract(\"timestamp\", \"day\", 1);\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param unit - The unit of time to subtract (e.g., \"day\", \"hour\").\n * @param amount - The amount of time to subtract.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp.\n */\nexport function timestampSubtract(\n  fieldName: string,\n  unit: TimeUnit,\n  amount: number\n): FunctionExpression;\nexport function timestampSubtract(\n  timestamp: Expression | string,\n  unit: TimeUnit | Expression,\n  amount: Expression | number\n): FunctionExpression {\n  const normalizedTimestamp = fieldOrExpression(timestamp);\n  const normalizedUnit = valueToDefaultExpr(unit);\n  const normalizedAmount = valueToDefaultExpr(amount);\n  return normalizedTimestamp.timestampSubtract(\n    normalizedUnit,\n    normalizedAmount\n  );\n}\n\n/**\n *\n * Creates an expression that evaluates to the current server timestamp.\n *\n * @example\n * ```typescript\n * // Get the current server timestamp\n * currentTimestamp()\n * ```\n *\n * @returns A new Expression representing the current server timestamp.\n */\nexport function currentTimestamp(): FunctionExpression {\n  return new FunctionExpression('current_timestamp', [], 'currentTimestamp');\n}\n\n/**\n *\n * Creates an expression that performs a logical 'AND' operation on multiple filter conditions.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18 AND the 'city' field is \"London\" AND\n * // the 'status' field is \"active\"\n * const condition = and(greaterThan(\"age\", 18), equal(\"city\", \"London\"), equal(\"status\", \"active\"));\n * ```\n *\n * @param first - The first filter condition.\n * @param second - The second filter condition.\n * @param more - Additional filter conditions to 'AND' together.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'AND' operation.\n */\nexport function and(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...more: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'and',\n    [first, second, ...more],\n    'and'\n  ).asBoolean();\n}\n\n/**\n *\n * Creates an expression that performs a logical 'OR' operation on multiple filter conditions.\n *\n * @example\n * ```typescript\n * // Check if the 'age' field is greater than 18 OR the 'city' field is \"London\" OR\n * // the 'status' field is \"active\"\n * const condition = or(greaterThan(\"age\", 18), equal(\"city\", \"London\"), equal(\"status\", \"active\"));\n * ```\n *\n * @param first - The first filter condition.\n * @param second - The second filter condition.\n * @param more - Additional filter conditions to 'OR' together.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'OR' operation.\n */\nexport function or(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...more: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'or',\n    [first, second, ...more],\n    'xor'\n  ).asBoolean();\n}\n\n/**\n *\n * Creates an expression that performs a logical 'NOR' operation on multiple filter conditions.\n *\n * @example\n * ```typescript\n * // Check if neither the 'age' field is greater than 18 nor the 'city' field is \"London\"\n * const condition = nor(\n *   greaterThan(\"age\", 18),\n *   equal(\"city\", \"London\")\n * );\n * ```\n *\n * @param first - The first filter condition.\n * @param second - The second filter condition.\n * @param more - Additional filter conditions to 'NOR' together.\n * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the logical 'NOR' operation.\n */\nexport function nor(\n  first: BooleanExpression,\n  second: BooleanExpression,\n  ...more: BooleanExpression[]\n): BooleanExpression {\n  return new FunctionExpression(\n    'nor',\n    [first, second, ...more],\n    'nor'\n  ).asBoolean();\n}\n\n/**\n * Creates an expression that returns the value of the base expression raised to the power of the exponent expression.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of the 'exponent' field.\n * pow(field(\"base\"), field(\"exponent\"));\n * ```\n *\n * @param base - The expression to raise to the power of the exponent.\n * @param exponent - The expression to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: Expression, exponent: Expression): FunctionExpression;\n\n/**\n * Creates an expression that returns the value of the base expression raised to the power of the exponent.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of 2.\n * pow(field(\"base\"), 2);\n * ```\n *\n * @param base - The expression to raise to the power of the exponent.\n * @param exponent - The constant value to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: Expression, exponent: number): FunctionExpression;\n\n/**\n * Creates an expression that returns the value of the base field raised to the power of the exponent expression.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of the 'exponent' field.\n * pow(\"base\", field(\"exponent\"));\n * ```\n *\n * @param base - The name of the field to raise to the power of the exponent.\n * @param exponent - The expression to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: string, exponent: Expression): FunctionExpression;\n\n/**\n * Creates an expression that returns the value of the base field raised to the power of the exponent.\n *\n * @example\n * ```typescript\n * // Raise the value of the 'base' field to the power of 2.\n * pow(\"base\", 2);\n * ```\n *\n * @param base - The name of the field to raise to the power of the exponent.\n * @param exponent - The constant value to raise the base to the power of.\n * @returns A new `Expression` representing the power operation.\n */\nexport function pow(base: string, exponent: number): FunctionExpression;\nexport function pow(\n  base: Expression | string,\n  exponent: Expression | number\n): FunctionExpression {\n  return fieldOrExpression(base).pow(exponent as number);\n}\n\n/**\n *\n * Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0.\n *\n * @example\n * ```typescript\n * // Generate a random number between 0.0 and 1.0.\n * rand();\n * ```\n *\n * @returns A new `Expression` representing the rand operation.\n */\nexport function rand(): FunctionExpression {\n  return new FunctionExpression('rand', [], 'rand');\n}\n\n/**\n * Creates an expression that rounds a numeric value to the nearest whole number.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field.\n * round(\"price\");\n * ```\n *\n * @param fieldName - The name of the field to round.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that rounds a numeric value to the nearest whole number.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field.\n * round(field(\"price\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be rounded.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(expression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that rounds a numeric value to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field to two decimal places.\n * round(\"price\", 2);\n * ```\n *\n * @param fieldName - The name of the field to round.\n * @param decimalPlaces - A constant or expression specifying the rounding precision in decimal places.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(\n  fieldName: string,\n  decimalPlaces: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that rounds a numeric value to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Round the value of the 'price' field to two decimal places.\n * round(field(\"price\"), constant(2));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be rounded.\n * @param decimalPlaces - A constant or expression specifying the rounding precision in decimal places.\n * @returns A new `Expression` representing the rounded value.\n */\nexport function round(\n  expression: Expression,\n  decimalPlaces: number | Expression\n): FunctionExpression;\nexport function round(\n  expr: Expression | string,\n  decimalPlaces?: number | Expression\n): FunctionExpression {\n  if (decimalPlaces === undefined) {\n    return fieldOrExpression(expr).round();\n  } else {\n    return fieldOrExpression(expr).round(valueToDefaultExpr(decimalPlaces));\n  }\n}\n\n/**\n * Creates an expression that truncates the numeric value of a field to an integer.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field\n * trunc(\"rating\");\n * ```\n *\n * @param fieldName - The name of the field containing the number to truncate.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that truncates the numeric value of an expression to an integer.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field.\n * trunc(field(\"rating\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be truncated.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(expression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that truncates a numeric expression to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field to two decimal places.\n * trunc(\"rating\", 2);\n * ```\n *\n * @param fieldName - The name of the field to truncate.\n * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(\n  fieldName: string,\n  decimalPlaces: number | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a numeric value to the specified number of decimal places.\n *\n * @example\n * ```typescript\n * // Truncate the value of the 'rating' field to two decimal places.\n * trunc(field(\"rating\"), constant(2));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which will be truncated.\n * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places.\n * @returns A new `Expression` representing the truncated value.\n */\nexport function trunc(\n  expression: Expression,\n  decimalPlaces: number | Expression\n): FunctionExpression;\nexport function trunc(\n  expr: Expression | string,\n  decimalPlaces?: number | Expression\n): FunctionExpression {\n  if (decimalPlaces === undefined) {\n    return fieldOrExpression(expr).trunc();\n  } else {\n    return fieldOrExpression(expr).trunc(valueToDefaultExpr(decimalPlaces));\n  }\n}\n\n/**\n * Creates an expression that returns the collection ID from a path.\n *\n * @example\n * ```typescript\n * // Get the collection ID from a path.\n * collectionId(\"__name__\");\n * ```\n *\n * @param fieldName - The name of the field to get the collection ID from.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.\n */\nexport function collectionId(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that returns the collection ID from a path.\n *\n * @example\n * ```typescript\n * // Get the collection ID from a path.\n * collectionId(field(\"__name__\"));\n * ```\n *\n * @param expression - An expression evaluating to a path, which the collection ID will be extracted from.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.\n */\nexport function collectionId(expression: Expression): FunctionExpression;\nexport function collectionId(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).collectionId();\n}\n\n/**\n * Creates an expression that calculates the length of a string, array, map, vector, or bytes.\n *\n * @example\n * ```typescript\n * // Get the length of the 'name' field.\n * length(\"name\");\n *\n * // Get the number of items in the 'cart' array.\n * length(\"cart\");\n * ```\n *\n * @param fieldName - The name of the field to calculate the length of.\n * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.\n */\nexport function length(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that calculates the length of a string, array, map, vector, or bytes.\n *\n * @example\n * ```typescript\n * // Get the length of the 'name' field.\n * length(field(\"name\"));\n *\n * // Get the number of items in the 'cart' array.\n * length(field(\"cart\"));\n * ```\n *\n * @param expression - An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for.\n * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.\n */\nexport function length(expression: Expression): FunctionExpression;\nexport function length(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).length();\n}\n\n/**\n * Creates an expression that computes the natural logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the natural logarithm of the 'value' field.\n * ln(\"value\");\n * ```\n *\n * @param fieldName - The name of the field to compute the natural logarithm of.\n * @returns A new `Expression` representing the natural logarithm of the numeric value.\n */\nexport function ln(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the natural logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the natural logarithm of the 'value' field.\n * ln(field(\"value\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the natural logarithm will be computed for.\n * @returns A new `Expression` representing the natural logarithm of the numeric value.\n */\nexport function ln(expression: Expression): FunctionExpression;\nexport function ln(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).ln();\n}\n\n/**\n * Creates an expression that computes the logarithm of an expression to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with base 10.\n * log(field(\"value\"), 10);\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the logarithm will be computed for.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(expression: Expression, base: number): FunctionExpression;\n/**\n * Creates an expression that computes the logarithm of an expression to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with the base in the 'base' field.\n * log(field(\"value\"), field(\"base\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the logarithm will be computed for.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(\n  expression: Expression,\n  base: Expression\n): FunctionExpression;\n/**\n * Creates an expression that computes the logarithm of a field to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with base 10.\n * log(\"value\", 10);\n * ```\n *\n * @param fieldName - The name of the field to compute the logarithm of.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(fieldName: string, base: number): FunctionExpression;\n/**\n * Creates an expression that computes the logarithm of a field to a given base.\n *\n * @example\n * ```typescript\n * // Compute the logarithm of the 'value' field with the base in the 'base' field.\n * log(\"value\", field(\"base\"));\n * ```\n *\n * @param fieldName - The name of the field to compute the logarithm of.\n * @param base - The base of the logarithm.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value.\n */\nexport function log(fieldName: string, base: Expression): FunctionExpression;\nexport function log(\n  expr: Expression | string,\n  base: number | Expression\n): FunctionExpression {\n  return new FunctionExpression('log', [\n    fieldOrExpression(expr),\n    valueToDefaultExpr(base)\n  ]);\n}\n\n/**\n * Creates an expression that computes the square root of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the square root of the 'value' field.\n * sqrt(field(\"value\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the square root will be computed for.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.\n */\nexport function sqrt(expression: Expression): FunctionExpression;\n/**\n * Creates an expression that computes the square root of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the square root of the 'value' field.\n * sqrt(\"value\");\n * ```\n *\n * @param fieldName - The name of the field to compute the square root of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.\n */\nexport function sqrt(fieldName: string): FunctionExpression;\nexport function sqrt(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).sqrt();\n}\n\n/**\n * Creates an expression that reverses a string.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * stringReverse(field(\"myString\"));\n * ```\n *\n * @param stringExpression - An expression evaluating to a string value, which will be reversed.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function stringReverse(stringExpression: Expression): FunctionExpression;\n\n/**\n * Creates an expression that reverses a string value in the specified field.\n *\n * @example\n * ```typescript\n * // Reverse the value of the 'myString' field.\n * stringReverse(\"myString\");\n * ```\n *\n * @param field - The name of the field representing the string to reverse.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.\n */\nexport function stringReverse(field: string): FunctionExpression;\nexport function stringReverse(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).stringReverse();\n}\n\n/**\n * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.\n *\n * @example\n * ```typescript\n * // Concatenate the 'firstName' and 'lastName' fields with a space in between.\n * concat(field(\"firstName\"), \" \", field(\"lastName\"))\n * ```\n *\n * @param first - The first expressions to concatenate.\n * @param second - The second literal or expression to concatenate.\n * @param others - Additional literals or expressions to concatenate.\n * @returns A new `Expression` representing the concatenation.\n */\nexport function concat(\n  first: Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.\n *\n * @example\n * ```typescript\n * // Concatenate a field with a literal string.\n * concat(field(\"firstName\"), \"Doe\")\n * ```\n *\n * @param fieldName - The name of a field to concatenate.\n * @param second - The second literal or expression to concatenate.\n * @param others - Additional literal or expressions to concatenate.\n * @returns A new `Expression` representing the concatenation.\n */\nexport function concat(\n  fieldName: string,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\nexport function concat(\n  fieldNameOrExpression: string | Expression,\n  second: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return new FunctionExpression('concat', [\n    fieldOrExpression(fieldNameOrExpression),\n    valueToDefaultExpr(second),\n    ...others.map(valueToDefaultExpr)\n  ]);\n}\n\n/**\n * Creates an expression that computes the absolute value of a numeric value.\n *\n * @param expr - The expression to compute the absolute value of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.\n */\nexport function abs(expr: Expression): FunctionExpression;\n\n/**\n * Creates an expression that computes the absolute value of a numeric value.\n *\n * @param fieldName - The field to compute the absolute value of.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.\n */\nexport function abs(fieldName: string): FunctionExpression;\nexport function abs(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).abs();\n}\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return\n * the result of the `ifExpr` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n * // if the field is absent.\n * ifAbsent(field(\"optional_field\"), constant(\"default_value\"))\n * ```\n *\n * @param ifExpr - The expression to check for absence.\n * @param elseExpr - The expression that will be evaluated and returned if [ifExpr] is absent.\n * @returns A new Expression representing the ifAbsent operation.\n */\nexport function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else\n * return the result of the `ifExpr` argument evaluation.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n * // if the field is absent.\n * ifAbsent(field(\"optional_field\"), \"default_value\")\n * ```\n *\n * @param ifExpr - The expression to check for absence.\n * @param elseValue - The value that will be returned if `ifExpr` evaluates to an absent value.\n * @returns A new [Expression] representing the ifAbsent operation.\n */\nexport function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression;\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else\n * return the value of the field.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns the value of\n * // 'default_field' if 'optional_field' is absent.\n * ifAbsent(\"optional_field\", field(\"default_field\"))\n * ```\n *\n * @param ifFieldName - The field to check for absence.\n * @param elseExpr - The expression that will be evaluated and returned if `ifFieldName` is\n * absent.\n * @returns A new Expression representing the ifAbsent operation.\n */\nexport function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifFieldName` is absent, else\n * return the value of the field.\n *\n * @example\n * ```typescript\n * // Returns the value of the optional field 'optional_field', or returns 'default_value'\n * // if the field is absent.\n * ifAbsent(\"optional_field\", \"default_value\")\n * ```\n *\n * @param ifFieldName - The field to check for absence.\n * @param elseValue - The value that will be returned if [ifFieldName] is absent.\n * @returns A new Expression representing the ifAbsent operation.\n */\nexport function ifAbsent(\n  ifFieldName: string | Expression,\n  elseValue: Expression | unknown\n): Expression;\nexport function ifAbsent(\n  fieldNameOrExpression: string | Expression,\n  elseValue: Expression | unknown\n): Expression {\n  return fieldOrExpression(fieldNameOrExpression).ifAbsent(\n    valueToDefaultExpr(elseValue)\n  );\n}\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifExpr` is null, else\n * return the result of the `ifExpr` argument evaluation.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's preferred name, or if that is null, returns their full name.\n * ifNull(field(\"preferredName\"), field(\"fullName\"))\n * ```\n *\n * @param ifExpr - The expression to check for null.\n * @param elseExpr - The expression that will be evaluated and returned if `ifExpr` is null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ifNull operation.\n */\nexport function ifNull(\n  ifExpr: Expression,\n  elseExpr: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifExpr` is null, else\n * return the result of the `ifExpr` argument evaluation.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's display name, or returns \"Anonymous\" if the field is null.\n * ifNull(field(\"displayName\"), \"Anonymous\")\n * ```\n *\n * @param ifExpr - The expression to check for null.\n * @param elseValue - The value that will be returned if `ifExpr` evaluates to null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ifNull operation.\n */\nexport function ifNull(\n  ifExpr: Expression,\n  elseValue: unknown\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the `elseExpr` argument if `ifFieldName` field is null, else\n * return the value of the field.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's preferred name, or if that is null, returns their full name.\n * ifNull(\"preferredName\", field(\"fullName\"))\n * ```\n *\n * @param ifFieldName - The field to check for null.\n * @param elseExpr - The expression that will be evaluated and returned if `ifFieldName` is null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ifNull operation.\n */\nexport function ifNull(\n  ifFieldName: string,\n  elseExpr: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the `elseValue` argument if `ifFieldName` field is null, else\n * return the value of the field.\n *\n * @remarks\n * This function provides a fallback for both absent and explicit null values. In contrast,\n * `ifAbsent()` only triggers for missing fields.\n *\n * @example\n * ```typescript\n * // Returns the user's display name, or returns \"Anonymous\" if the field is null.\n * ifNull(\"displayName\", \"Anonymous\")\n * ```\n *\n * @param ifFieldName - The field to check for null.\n * @param elseValue - The value that will be returned if `ifFieldName` is null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression}  representing the ifNull operation.\n */\nexport function ifNull(\n  ifFieldName: string,\n  elseValue: unknown\n): FunctionExpression;\nexport function ifNull(\n  fieldNameOrExpression: string | Expression,\n  elseValue: Expression | unknown\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).ifNull(elseValue);\n}\n\n/**\n * Creates an expression that returns the first non-null, non-absent argument, without evaluating\n * the rest of the arguments. When all arguments are null or absent, returns the last argument.\n *\n * @example\n * ```typescript\n * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',\n * // or the last argument if all previous fields are null.\n * coalesce(field(\"preferredName\"), field(\"fullName\"), constant(\"Anonymous\"))\n * ```\n *\n * @param expression - The first expression to check for null.\n * @param replacement - The fallback expression or value if the first one is null.\n * @param others - Optional additional expressions to check if previous ones are null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the coalesce operation.\n */\nexport function coalesce(\n  expression: Expression,\n  replacement: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\n\n/**\n * Creates an expression that returns the first non-null, non-absent argument, without evaluating\n * the rest of the arguments. When all arguments are null or absent, returns the last argument.\n *\n * @example\n * ```typescript\n * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',\n * // or the last argument if all previous fields are null.\n * coalesce(\"preferredName\", field(\"fullName\"), constant(\"Anonymous\"))\n * ```\n *\n * @param fieldName - The name of the first field to check for null.\n * @param replacement - The fallback expression or value if the first one is null.\n * @param others - Optional additional expressions to check if previous ones are null.\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the coalesce operation.\n */\nexport function coalesce(\n  fieldName: string,\n  replacement: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression;\nexport function coalesce(\n  fieldNameOrExpression: Expression | string,\n  replacement: Expression | unknown,\n  ...others: Array<Expression | unknown>\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).coalesce(\n    replacement,\n    ...others\n  );\n}\n\n/**\n * Creates an expression that evaluates to the result corresponding to the first true condition.\n *\n * @remarks\n * This function behaves like a `switch` statement. It accepts an alternating sequence of conditions\n * and their corresponding results.\n * If an odd number of arguments is provided, the final argument serves as a default fallback result.\n * If no default is provided and no condition evaluates to true, it throws an error.\n *\n * @example\n * ```typescript\n * // Return \"Active\" if field \"status\" is 1, \"Pending\" if field \"status\" is 2,\n * // and default to \"Unknown\" if none of the conditions are true.\n * switchOn(\n *   equal(field(\"status\"), 1), constant(\"Active\"),\n *   equal(field(\"status\"), 2), constant(\"Pending\"),\n *   constant(\"Unknown\")\n * )\n * ```\n *\n * @param condition - The first condition to check.\n * @param result - The result if the first condition is true.\n * @param others - Additional conditions and results, and optionally a default value.\n * @returns A new Expression representing the switch operation.\n */\nexport function switchOn(\n  condition: BooleanExpression,\n  result: Expression,\n  ...others: Array<BooleanExpression | Expression>\n): FunctionExpression {\n  return new FunctionExpression(\n    'switch_on',\n    [\n      valueToDefaultExpr(condition),\n      valueToDefaultExpr(result),\n      ...others.map(valueToDefaultExpr)\n    ],\n    'switchOn'\n  );\n}\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join the elements of the 'tags' field with a comma and space.\n * join(\"tags\", \", \")\n * ```\n *\n * @param arrayFieldName - The name of the field containing the array.\n * @param delimiter - The string to use as a delimiter.\n * @returns A new Expression representing the join operation.\n */\nexport function join(arrayFieldName: string, delimiter: string): Expression;\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join an array of string using the delimiter from the 'separator' field.\n * join(array(['foo', 'bar']), field(\"separator\"))\n * ```\n *\n * @param arrayExpression - An expression that evaluates to an array.\n * @param delimiterExpression - The expression that evaluates to the delimiter string.\n * @returns A new Expression representing the join operation.\n */\nexport function join(\n  arrayExpression: Expression,\n  delimiterExpression: Expression\n): Expression;\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join the elements of the 'tags' field with a comma and space.\n * join(field(\"tags\"), \", \")\n * ```\n *\n * @param arrayExpression - An expression that evaluates to an array.\n * @param delimiter - The string to use as a delimiter.\n * @returns A new Expression representing the join operation.\n */\nexport function join(\n  arrayExpression: Expression,\n  delimiter: string\n): Expression;\n\n/**\n * Creates an expression that joins the elements of an array into a string.\n *\n * @example\n * ```typescript\n * // Join the elements of the 'tags' field with the delimiter from the 'separator' field.\n * join('tags', field(\"separator\"))\n * ```\n *\n * @param arrayFieldName - The name of the field containing the array.\n * @param delimiterExpression - The expression that evaluates to the delimiter string.\n * @returns A new Expression representing the join operation.\n */\nexport function join(\n  arrayFieldName: string,\n  delimiterExpression: Expression\n): Expression;\nexport function join(\n  fieldNameOrExpression: string | Expression,\n  delimiterValueOrExpression: Expression | string\n): Expression {\n  return fieldOrExpression(fieldNameOrExpression).join(\n    valueToDefaultExpr(delimiterValueOrExpression)\n  );\n}\n\n/**\n * Creates an expression that computes the base-10 logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the base-10 logarithm of the 'value' field.\n * log10(\"value\");\n * ```\n *\n * @param fieldName - The name of the field to compute the base-10 logarithm of.\n * @returns A new `Expression` representing the base-10 logarithm of the numeric value.\n */\nexport function log10(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the base-10 logarithm of a numeric value.\n *\n * @example\n * ```typescript\n * // Compute the base-10 logarithm of the 'value' field.\n * log10(field(\"value\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric value, which the base-10 logarithm will be computed for.\n * @returns A new `Expression` representing the base-10 logarithm of the numeric value.\n */\nexport function log10(expression: Expression): FunctionExpression;\nexport function log10(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).log10();\n}\n\n/**\n * Creates an expression that computes the sum of the elements in an array.\n *\n * @example\n * ```typescript\n * // Compute the sum of the elements in the 'scores' field.\n * arraySum(\"scores\");\n * ```\n *\n * @param fieldName - The name of the field to compute the sum of.\n * @returns A new `Expression` representing the sum of the elements in the array.\n */\nexport function arraySum(fieldName: string): FunctionExpression;\n\n/**\n * Creates an expression that computes the sum of the elements in an array.\n *\n * @example\n * ```typescript\n * // Compute the sum of the elements in the 'scores' field.\n * arraySum(field(\"scores\"));\n * ```\n *\n * @param expression - An expression evaluating to a numeric array, which the sum will be computed for.\n * @returns A new `Expression` representing the sum of the elements in the array.\n */\nexport function arraySum(expression: Expression): FunctionExpression;\nexport function arraySum(expr: Expression | string): FunctionExpression {\n  return fieldOrExpression(expr).arraySum();\n}\n\n/**\n * Creates an expression that splits the value of a field on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scoresCsv' field on delimiter ','\n * split('scoresCsv', ',')\n * ```\n *\n * @param fieldName - Split the value in this field.\n * @param delimiter - Split on this delimiter.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(fieldName: string, delimiter: string): FunctionExpression;\n\n/**\n * Creates an expression that splits the value of a field on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format\n * split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')))\n * ```\n *\n * @param fieldName - Split the value in this field.\n * @param delimiter - Split on this delimiter returned by evaluating this expression.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(\n  fieldName: string,\n  delimiter: Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that splits a string into an array of substrings based on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scoresCsv' field on delimiter ','\n * split(field('scoresCsv'), ',')\n * ```\n *\n * @param expression - Split the result of this expression.\n * @param delimiter - Split on this delimiter.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(\n  expression: Expression,\n  delimiter: string\n): FunctionExpression;\n\n/**\n * Creates an expression that splits a string into an array of substrings based on the provided delimiter.\n *\n * @example\n * ```typescript\n * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format\n * split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')))\n * ```\n *\n * @param expression - Split the result of this expression.\n * @param delimiter - Split on this delimiter returned by evaluating this expression.\n *\n * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function.\n */\nexport function split(\n  expression: Expression,\n  delimiter: Expression\n): FunctionExpression;\nexport function split(\n  fieldNameOrExpression: string | Expression,\n  delimiter: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).split(\n    valueToDefaultExpr(delimiter)\n  );\n}\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the beginning of the day.\n * timestampTruncate('createdAt', 'day')\n * ```\n *\n * @param fieldName - Truncate the timestamp value contained in this field.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  fieldName: string,\n  granularity: TimeGranularity,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.\n * timestampTruncate('createdAt', field('granularity'))\n * ```\n *\n * @param fieldName - Truncate the timestamp value contained in this field.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  fieldName: string,\n  granularity: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the beginning of the day.\n * timestampTruncate(field('createdAt'), 'day')\n * ```\n *\n * @param timestampExpression - Truncate the timestamp value that is returned by this expression.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  timestampExpression: Expression,\n  granularity: TimeGranularity,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that truncates a timestamp to a specified granularity.\n *\n * @example\n * ```typescript\n * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.\n * timestampTruncate(field('createdAt'), field('granularity'))\n * ```\n *\n * @param timestampExpression - Truncate the timestamp value that is returned by this expression.\n * @param granularity - The granularity to truncate to.\n * @param timezone - The timezone to use for truncation. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1\".\n * @returns A new `Expression` representing the truncated timestamp.\n */\nexport function timestampTruncate(\n  timestampExpression: Expression,\n  granularity: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\nexport function timestampTruncate(\n  fieldNameOrExpression: string | Expression,\n  granularity: TimeGranularity | Expression,\n  timezone?: string | Expression\n): FunctionExpression {\n  const internalGranularity = isString(granularity)\n    ? valueToDefaultExpr(granularity)\n    : granularity;\n  return fieldOrExpression(fieldNameOrExpression).timestampTruncate(\n    internalGranularity,\n    timezone\n  );\n}\n\n/**\n * @public\n * Creates an expression that retrieves the value of a variable bound via `define()`.\n *\n * @example\n * ```typescript\n * db.pipeline().collection(\"products\")\n *   .define(\n *     field(\"price\").multiply(0.9).as(\"discountedPrice\"),\n *     field(\"stock\").add(10).as(\"newStock\")\n *   )\n *   .where(variable(\"discountedPrice\").lessThan(100))\n *   .select(field(\"name\"), variable(\"newStock\"));\n * ```\n *\n * @param name - The name of the variable to retrieve.\n * @returns An {@link @firebase/firestore/pipelines#Expression} representing the variable's value.\n */\nexport function variable(name: string): Expression {\n  return new VariableExpression(name);\n}\n\n/**\n * @internal\n *\n * Expression representing a variable reference. This evaluates to the value of a variable\n * defined in a pipeline.\n */\nexport class VariableExpression extends Expression {\n  readonly _methodName?: string | undefined;\n\n  /**\n   * @hideconstructor\n   */\n  constructor(private readonly name: string) {\n    super();\n  }\n\n  expressionType: ExpressionType = 'Variable';\n\n  /**\n   * @internal\n   */\n  _toProto(_: JsonProtoSerializer): ProtoValue {\n    return {\n      variableReferenceValue: this.name\n    };\n  }\n\n  /**\n   * @internal\n   */\n  _readUserData(_: ParseContext): void {}\n}\n\n/**\n * @public\n * Creates an expression that represents the current document being processed.\n *\n * @example\n * ```typescript\n * // Define the current document as a variable \"doc\"\n * firestore.pipeline().collection(\"books\")\n *     .define(currentDocument().as(\"doc\"))\n *     // Access a field from the defined document variable\n *     .select(variable(\"doc\").mapGet(\"title\"));\n * ```\n *\n * @returns An {@link @firebase/firestore/pipelines#Expression} representing the current document.\n */\nexport function currentDocument(): Expression {\n  return new FunctionExpression('current_document', []);\n}\n\n/**\n * @internal\n */\nexport function pipelineValue(pipeline: Pipeline): PipelineValueExpression {\n  return new PipelineValueExpression(pipeline);\n}\n\n/**\n * @internal\n */\nclass PipelineValueExpression extends Expression {\n  readonly _methodName?: string | undefined;\n  expressionType: ExpressionType = 'PipelineValue';\n\n  /**\n   * @hideconstructor\n   */\n  constructor(private readonly pipeline: Pipeline) {\n    super();\n  }\n\n  /**\n   * @internal\n   */\n  _toProto(jsonProtoSerializer: JsonProtoSerializer): ProtoValue {\n    return toPipelineValue(this.pipeline._toProto(jsonProtoSerializer));\n  }\n\n  /**\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.pipeline._readUserData(context);\n  }\n}\n\n/*\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between 'endTime' and 'startTime' fields.\n * timestampDiff('endTime', 'startTime', 'day')\n * ```\n *\n * @param endFieldName - The name of the field representing the ending timestamp.\n * @param startFieldName - The name of the field representing the starting timestamp.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endFieldName: string,\n  startFieldName: string,\n  unit: TimeUnit | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between 'endTime' field and a starting timestamp expression.\n * timestampDiff('endTime', field('startTime'), 'day')\n * ```\n *\n * @param endFieldName - The name of the field representing the ending timestamp.\n * @param startExpression - The starting timestamp for the difference calculation.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endFieldName: string,\n  startExpression: Expression,\n  unit: TimeUnit | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between an ending timestamp expression and 'startTime' field.\n * timestampDiff(field('endTime'), 'startTime', 'day')\n * ```\n *\n * @param endExpression - The ending timestamp for the difference calculation.\n * @param startFieldName - The name of the field representing the starting timestamp.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endExpression: Expression,\n  startFieldName: string,\n  unit: TimeUnit | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that calculates the difference between two timestamps.\n *\n * @example\n * ```typescript\n * // Calculate the difference in days between two timestamp expressions.\n * timestampDiff(field('endTime'), field('startTime'), 'day')\n * ```\n *\n * @param endExpression - The ending timestamp for the difference calculation.\n * @param startExpression - The starting timestamp for the difference calculation.\n * @param unit - The unit of time for the difference (e.g., \"day\", \"hour\").\n * @returns A new `Expression` representing the difference as an integer.\n */\nexport function timestampDiff(\n  endExpression: Expression,\n  startExpression: Expression,\n  unit: TimeUnit | Expression\n): FunctionExpression;\nexport function timestampDiff(\n  endFieldNameOrExpression: string | Expression,\n  startFieldNameOrExpression: string | Expression,\n  unit: TimeUnit | Expression\n): FunctionExpression {\n  const normalizedEnd = fieldOrExpression(endFieldNameOrExpression);\n  const normalizedStart = fieldOrExpression(startFieldNameOrExpression);\n  const normalizedUnit = valueToDefaultExpr(unit);\n  return normalizedEnd.timestampDiff(normalizedStart, normalizedUnit);\n}\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the year from the 'createdAt' timestamp.\n * timestampExtract('createdAt', 'year')\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param part - The part to extract from the timestamp (e.g., \"year\", \"month\", \"day\").\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  fieldName: string,\n  part: TimePart,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the part specified by the field 'part' from 'createdAt'.\n * timestampExtract('createdAt', field('part'))\n * ```\n *\n * @param fieldName - The name of the field representing the timestamp.\n * @param part - The expression evaluating to the part to extract.\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  fieldName: string,\n  part: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the year from the timestamp returned by the expression.\n * timestampExtract(field('createdAt'), 'year')\n * ```\n *\n * @param timestampExpression - The expression evaluating to the timestamp.\n * @param part - The part to extract from the timestamp (e.g., \"year\", \"month\", \"day\").\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  timestampExpression: Expression,\n  part: TimePart,\n  timezone?: string | Expression\n): FunctionExpression;\n\n/**\n * Creates an expression that extracts a specified part from a timestamp.\n *\n * @example\n * ```typescript\n * // Extract the part specified by the field 'part' from the timestamp.\n * timestampExtract(field('createdAt'), field('part'))\n * ```\n *\n * @param timestampExpression - The expression evaluating to the timestamp.\n * @param part - The expression evaluating to the part to extract.\n * @param timezone - The timezone to use for extraction. Valid values are from\n * the TZ database (e.g., \"America/Los_Angeles\") or in the format \"Etc/GMT-1.\"\n * @returns A new `Expression` representing the extracted part as an integer.\n */\nexport function timestampExtract(\n  timestampExpression: Expression,\n  part: Expression,\n  timezone?: string | Expression\n): FunctionExpression;\nexport function timestampExtract(\n  fieldNameOrExpression: string | Expression,\n  part: TimePart | Expression,\n  timezone?: string | Expression\n): FunctionExpression {\n  return fieldOrExpression(fieldNameOrExpression).timestampExtract(\n    valueToDefaultExpr(part),\n    timezone\n  );\n}\n\n// TODO(search) enable with backend support\n// /**\n//  * Perform a full-text search on the specified field.\n//  *\n//  * @remarks This Expression can only be used within a `search` stage.\n//  *\n//  * @example\n//  * ```typescript\n//  * db.pipeline().collection('restaurants').search({\n//  *   query: matches('menu', 'waffles')\n//  * })\n//  * ```\n//  *\n//  * @param searchField Search the specified field.\n//  * @param rquery Define the search query using the search domain-specific language (DSL).\n//  */\n// export function matches(\n//   searchField: string | Field,\n//   rquery: string | Expression\n// ): BooleanExpression {\n//   return toField(searchField).matches(rquery);\n// }\n\n/**\n * @beta\n * Perform a full-text search on all indexed search fields in the document.\n *\n * @remarks This Expression can only be used within a `search` stage.\n *\n * @example\n * ```typescript\n * db.pipeline().collection('restaurants').search({\n *   query: documentMatches('waffles OR pancakes')\n * })\n * ```\n *\n * @param rquery Define the search query using the search domain-specific language (DSL).\n */\nexport function documentMatches(\n  rquery: string | Expression\n): BooleanExpression {\n  return new FunctionExpression(\n    'document_matches',\n    [valueToDefaultExpr(rquery)],\n    'documentMatches'\n  ).asBoolean();\n}\n\n/**\n * @beta\n *\n * Evaluates to the search score that reflects the topicality of the document\n * to all of the text predicates (for example: `documentMatches`)\n * in the search query. If `SearchOptions.query` is not set or does not contain\n * any text predicates, then this topicality score will always be `0`.\n *\n * @example\n * ```typescript\n * db.pipeline().collection('restaurants').search({\n *   query: 'waffles',\n *   sort: score().descending()\n * })\n * ```\n *\n * @remarks This Expression can only be used within a `search` stage.\n */\nexport function score(): Expression {\n  return new FunctionExpression('score', [], 'score');\n}\n\n// TODO(search) enable with backend support\n// /**\n//  * Options defining how a snippet expression is evaluated.\n//  */\n// export interface SnippetOptions {\n//   /**\n//    * Define the search query using the search domain-specific language (DSL).\n//    */\n//   rquery: string;\n//\n//   /**\n//    * The maximum width of the string estimated for a variable width font. The\n//    * unit is tenths of ems. The default is `160`.\n//    */\n//   maxSnippetWidth?: number;\n//\n//   /**\n//    * The maximum number of non-contiguous pieces of text in the returned snippet.\n//    * The default is `1`.\n//    */\n//   maxSnippets?: number;\n//\n//   /**\n//    * The string to join the pieces. The default value is '\\n'\n//    */\n//   separator?: string;\n// }\n//\n// /**\n//  * Evaluates to an HTML-formatted text snippet that highlights terms matching\n//  * the search query in `<b>bold</b>`.\n//  *\n//  * @remarks This Expression can only be used within a `search` stage.\n//  *\n//  * @example\n//  * ```typescript\n//  * db.pipeline().collection('restaurants').search({\n//  *   query: 'waffles',\n//  *   addFields: { snippet: snippet('menu', 'waffles') }\n//  * })\n//  * ```\n//  *\n//  * @param searchField Search the specified field for matching terms.\n//  * @param rquery Define the search query using the search domain-specific language (DSL).\n//  */\n// export function snippet(\n//   searchField: string | Field,\n//   rquery: string\n// ): Expression;\n//\n// /**\n//  * Evaluates to an HTML-formatted text snippet that highlights terms matching\n//  * the search query in `<b>bold</b>`.\n//  *\n//  * @remarks This Expression can only be used within a `search` stage.\n//  *\n//  * @param searchField Search the specified field for matching terms.\n//  * @param options Define the search query using the search domain-specific language (DSL).\n//  */\n// export function snippet(\n//   searchField: string | Field,\n//   options: SnippetOptions\n// ): Expression;\n// export function snippet(\n//   field: string | Field,\n//   queryOrOptions: string | SnippetOptions\n// ): Expression {\n//   return toField(field).snippet(\n//     isString(queryOrOptions) ? { rquery: queryOrOptions } : queryOrOptions\n//   );\n// }\n\n/**\n * @beta\n * Evaluates to the distance in meters between the location in the specified\n * field and the query location.\n *\n * @remarks This Expression can only be used within a `search` stage.\n *\n * @example\n * ```typescript\n * db.pipeline().collection('restaurants').search({\n *   query: 'waffles',\n *   sort: geoDistance('location', new GeoPoint(37.0, -122.0)).ascending()\n * })\n * ```\n *\n * @param fieldName - Specifies the field in the document which contains\n * the first GeoPoint for distance computation.\n * @param location - Compute distance to this GeoPoint.\n */\nexport function geoDistance(\n  fieldName: string | Field,\n  location: GeoPoint | Expression\n): Expression {\n  return toField(fieldName).geoDistance(location);\n}\n\n// TODO(search) enable with backend support\n// /**\n//  * Evaluates if the value in the field specified by `fieldName` is between\n//  * the evaluated values for `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between('tireWidth', constant(2.2), constant(2.4))\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual('tireWidth', constant(2.2)), lessThanOrEqual('tireWidth', constant(2.4)))\n//  * ```\n//  *\n//  * @param fieldName - Evaluate if the value stored in this field is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   fieldName: string,\n//   lowerBound: Expression,\n//   upperBound: Expression\n// ): BooleanExpression;\n//\n// /**\n//  * Evaluates if the value in the field specified by `fieldName` is between\n//  * the values for `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between('tireWidth', 2.2, 2.4)\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual('tireWidth', 2.2), lessThanOrEqual('tireWidth', 2.4))\n//  * ```\n//  *\n//  * @param fieldName - Evaluate if the value stored in this field is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   fieldName: string,\n//   lowerBound: unknown,\n//   upperBound: unknown\n// ): BooleanExpression;\n//\n// /**\n//  * Evaluates if the result of the specified `expression` is between\n//  * the results of `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between(field('tireWidth'), constant(2.2), constant(2.4))\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual(field('tireWidth'), constant(2.2)), lessThanOrEqual(field('tireWidth'), constant(2.4)))\n//  * ```\n//  *\n//  * @param expression - Evaluate if the result of this expression is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   expression: Expression,\n//   lowerBound: Expression,\n//   upperBound: Expression\n// ): BooleanExpression;\n//\n// /**\n//  * Evaluates if the result of the specified `expression` is between\n//  * the `lowerBound` (inclusive) and `upperBound` (inclusive).\n//  *\n//  * @example\n//  * ```\n//  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4\n//  * between(field('tireWidth'), 2.2, 2.4)\n//  *\n//  * // This is functionally equivalent to\n//  * and(greaterThanOrEqual(field('tireWidth'), 2.2), lessThanOrEqual(field('tireWidth'), 2.4))\n//  * ```\n//  *\n//  * @param expression - Evaluate if the result of this expression is between the lower and upper bounds.\n//  * @param lowerBound - Lower bound (inclusive) of the range.\n//  * @param upperBound - Upper bound (inclusive) of the range.\n//  */\n// export function between(\n//   expression: Expression,\n//   lowerBound: unknown,\n//   upperBound: unknown\n// ): BooleanExpression;\n//\n// export function between(\n//   expression: Expression | string,\n//   lowerBound: unknown,\n//   upperBound: unknown\n// ): BooleanExpression {\n//   return fieldOrExpression(expression).between(lowerBound, upperBound);\n// }\n\n// TODO(new-expression): Add new top-level expression function definitions above this line\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on an expression.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in lowercase in ascending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(ascending(field(\"name\").toLower()));\n * ```\n *\n * @param expr - The expression to create an ascending ordering for.\n * @returns A new `Ordering` for ascending sorting.\n */\nexport function ascending(expr: Expression): Ordering;\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on a field.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in ascending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(ascending(\"name\"));\n * ```\n *\n * @param fieldName - The field to create an ascending ordering for.\n * @returns A new `Ordering` for ascending sorting.\n */\nexport function ascending(fieldName: string): Ordering;\nexport function ascending(field: Expression | string): Ordering {\n  return new Ordering(fieldOrExpression(field), 'ascending', 'ascending');\n}\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on an expression.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in lowercase in descending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(descending(field(\"name\").toLower()));\n * ```\n *\n * @param expr - The expression to create a descending ordering for.\n * @returns A new `Ordering` for descending sorting.\n */\nexport function descending(expr: Expression): Ordering;\n\n/**\n *\n * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on a field.\n *\n * @example\n * ```typescript\n * // Sort documents by the 'name' field in descending order\n * firestore.pipeline().collection(\"users\")\n *   .sort(descending(\"name\"));\n * ```\n *\n * @param fieldName - The field to create a descending ordering for.\n * @returns A new `Ordering` for descending sorting.\n */\nexport function descending(fieldName: string): Ordering;\nexport function descending(field: Expression | string): Ordering {\n  return new Ordering(fieldOrExpression(field), 'descending', 'descending');\n}\n\n/**\n *\n * Represents an ordering criterion for sorting documents in a Firestore pipeline.\n *\n * You create `Ordering` instances using the `ascending` and `descending` helper functions.\n */\nexport class Ordering implements ProtoValueSerializable, UserData {\n  constructor(\n    public readonly expr: Expression,\n    public readonly direction: 'ascending' | 'descending',\n    readonly _methodName: string | undefined\n  ) {}\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoValue {\n    return {\n      mapValue: {\n        fields: {\n          direction: toStringValue(this.direction),\n          expression: this.expr._toProto(serializer)\n        }\n      }\n    };\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _readUserData(context: ParseContext): void {\n    this.expr._readUserData(context);\n  }\n\n  _protoValueType: 'ProtoValue' = 'ProtoValue';\n}\n\nexport function isSelectable(val: unknown): val is Selectable {\n  const candidate = val as Selectable;\n  return (\n    candidate.selectable && isString(candidate.alias) && isExpr(candidate.expr)\n  );\n}\n\nexport function isOrdering(val: unknown): val is Ordering {\n  const candidate = val as Ordering | undefined;\n  return (\n    candidate !== undefined &&\n    candidate !== null &&\n    isExpr(candidate.expr) &&\n    (candidate.direction === 'ascending' ||\n      candidate.direction === 'descending')\n  );\n}\n\nexport function isAliasedAggregate(val: unknown): val is AliasedAggregate {\n  const candidate = val as AliasedAggregate;\n  return (\n    isString(candidate.alias) &&\n    candidate.aggregate instanceof AggregateFunction\n  );\n}\n\nexport function isExpr(val: unknown): val is Expression {\n  return val instanceof Expression;\n}\n\nexport function isBooleanExpr(val: unknown): val is BooleanExpression {\n  return val instanceof BooleanExpression;\n}\n\nexport function isAliasedExpr(val: unknown): val is AliasedExpression {\n  return val instanceof AliasedExpression;\n}\n\nexport function isField(val: unknown): val is Field {\n  return val instanceof Field;\n}\n\nexport function toField(value: string | Field): Field {\n  if (isString(value)) {\n    const result = field(value);\n    return result;\n  } else {\n    return value as Field;\n  }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Firestore } from '../lite-api/database';\nimport {\n  Constant,\n  BooleanExpression,\n  and,\n  or,\n  Ordering,\n  lessThan,\n  greaterThan,\n  field\n} from '../lite-api/expressions';\nimport { Pipeline } from '../lite-api/pipeline';\nimport { doc } from '../lite-api/reference';\nimport { fail } from '../util/assert';\n\nimport { Bound } from './bound';\nimport {\n  CompositeFilter as CompositeFilterInternal,\n  CompositeOperator,\n  FieldFilter as FieldFilterInternal,\n  Filter as FilterInternal,\n  Operator\n} from './filter';\nimport { Direction } from './order_by';\nimport {\n  isCollectionGroupQuery,\n  isDocumentQuery,\n  LimitType,\n  Query,\n  queryNormalizedOrderBy\n} from './query';\n\n/* eslint @typescript-eslint/no-explicit-any: 0 */\n\nexport function toPipelineBooleanExpr(f: FilterInternal): BooleanExpression {\n  if (f instanceof FieldFilterInternal) {\n    const fieldValue = field(f.field.toString());\n    // Comparison filters\n    const value = f.value;\n    switch (f.op) {\n      case Operator.LESS_THAN:\n        return and(\n          fieldValue.exists(),\n          fieldValue.lessThan(Constant._fromProto(value))\n        );\n      case Operator.LESS_THAN_OR_EQUAL:\n        return and(\n          fieldValue.exists(),\n          fieldValue.lessThanOrEqual(Constant._fromProto(value))\n        );\n      case Operator.GREATER_THAN:\n        return and(\n          fieldValue.exists(),\n          fieldValue.greaterThan(Constant._fromProto(value))\n        );\n      case Operator.GREATER_THAN_OR_EQUAL:\n        return and(\n          fieldValue.exists(),\n          fieldValue.greaterThanOrEqual(Constant._fromProto(value))\n        );\n      case Operator.EQUAL:\n        return and(\n          fieldValue.exists(),\n          fieldValue.equal(Constant._fromProto(value))\n        );\n      case Operator.NOT_EQUAL:\n        return fieldValue.notEqual(Constant._fromProto(value));\n      case Operator.ARRAY_CONTAINS:\n        return and(\n          fieldValue.exists(),\n          fieldValue.arrayContains(Constant._fromProto(value))\n        );\n      case Operator.IN: {\n        const values = value?.arrayValue?.values?.map((val: any) =>\n          Constant._fromProto(val)\n        );\n        if (!values) {\n          return and(fieldValue.exists(), fieldValue.equalAny([]));\n        } else if (values.length === 1) {\n          return and(fieldValue.exists(), fieldValue.equal(values[0]));\n        } else {\n          return and(fieldValue.exists(), fieldValue.equalAny(values));\n        }\n      }\n      case Operator.ARRAY_CONTAINS_ANY: {\n        const values = value?.arrayValue?.values?.map((val: any) =>\n          Constant._fromProto(val)\n        );\n        return and(fieldValue.exists(), fieldValue.arrayContainsAny(values!));\n      }\n      case Operator.NOT_IN: {\n        const values = value?.arrayValue?.values?.map((val: any) =>\n          Constant._fromProto(val)\n        );\n        if (!values) {\n          return fieldValue.notEqualAny([]);\n        } else if (values.length === 1) {\n          return fieldValue.notEqual(values[0]);\n        } else {\n          return fieldValue.notEqualAny(values);\n        }\n      }\n      default:\n        fail(0x9047, 'Unexpected operator');\n    }\n  } else if (f instanceof CompositeFilterInternal) {\n    switch (f.op) {\n      case CompositeOperator.AND: {\n        const conditions = f.getFilters().map(f => toPipelineBooleanExpr(f));\n        return and(conditions[0], conditions[1], ...conditions.slice(2));\n      }\n      case CompositeOperator.OR: {\n        const conditions = f.getFilters().map(f => toPipelineBooleanExpr(f));\n        return or(conditions[0], conditions[1], ...conditions.slice(2));\n      }\n      default:\n        fail(0x89ea, 'Unexpected operator');\n    }\n  }\n\n  throw new Error(`Failed to convert filter to pipeline conditions: ${f}`);\n}\n\nfunction reverseOrderings(orderings: Ordering[]): Ordering[] {\n  return orderings.map(\n    o =>\n      new Ordering(\n        o.expr,\n        o.direction === 'ascending' ? 'descending' : 'ascending',\n        undefined\n      )\n  );\n}\n\nexport function toPipeline(query: Query, db: Firestore): Pipeline {\n  let pipeline: Pipeline;\n  if (isCollectionGroupQuery(query)) {\n    pipeline = db.pipeline().collectionGroup(query.collectionGroup!);\n  } else if (isDocumentQuery(query)) {\n    pipeline = db.pipeline().documents([doc(db, query.path.canonicalString())]);\n  } else {\n    pipeline = db.pipeline().collection(query.path.canonicalString());\n  }\n\n  // filters\n  for (const filter of query.filters) {\n    pipeline = pipeline.where(toPipelineBooleanExpr(filter));\n  }\n\n  // orders\n  const orders = queryNormalizedOrderBy(query);\n  const existsConditions = query.explicitOrderBy.map(order =>\n    field(order.field.canonicalString()).exists()\n  );\n  if (existsConditions.length > 0) {\n    const condition =\n      existsConditions.length === 1\n        ? existsConditions[0]\n        : and(\n            existsConditions[0],\n            existsConditions[1],\n            ...existsConditions.slice(2)\n          );\n    pipeline = pipeline.where(condition);\n  }\n\n  const orderings = orders.map(order =>\n    order.dir === Direction.ASCENDING\n      ? field(order.field.canonicalString()).ascending()\n      : field(order.field.canonicalString()).descending()\n  );\n\n  if (orderings.length > 0) {\n    if (query.limitType === LimitType.Last) {\n      const actualOrderings = reverseOrderings(orderings);\n      pipeline = pipeline.sort(actualOrderings[0], ...actualOrderings.slice(1));\n      // cursors\n      if (query.startAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.startAt, orderings, 'after')\n        );\n      }\n\n      if (query.endAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.endAt, orderings, 'before')\n        );\n      }\n\n      pipeline = pipeline.limit(query.limit!);\n      pipeline = pipeline.sort(orderings[0], ...orderings.slice(1));\n    } else {\n      pipeline = pipeline.sort(orderings[0], ...orderings.slice(1));\n      if (query.startAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.startAt, orderings, 'after')\n        );\n      }\n      if (query.endAt !== null) {\n        pipeline = pipeline.where(\n          whereConditionsFromCursor(query.endAt, orderings, 'before')\n        );\n      }\n\n      if (query.limit !== null) {\n        pipeline = pipeline.limit(query.limit);\n      }\n    }\n  }\n\n  return pipeline;\n}\n\nfunction whereConditionsFromCursor(\n  bound: Bound,\n  orderings: Ordering[],\n  position: 'before' | 'after'\n): BooleanExpression {\n  // The filterFunc is either greater than or less than\n  const filterFunc = position === 'before' ? lessThan : greaterThan;\n  const cursors = bound.position.map(value => Constant._fromProto(value));\n  const size = cursors.length;\n\n  let field = orderings[size - 1].expr;\n  let value = cursors[size - 1];\n\n  // Add condition for last bound\n  let condition: BooleanExpression = filterFunc(field, value);\n  if (bound.inclusive) {\n    // When the cursor bound is inclusive, then the last bound\n    // can be equal to the value, otherwise it's not equal\n    condition = or(condition, field.equal(value));\n  }\n\n  // Iterate backwards over the remaining bounds, adding\n  // a condition for each one\n  for (let i = size - 2; i >= 0; i--) {\n    field = orderings[i].expr;\n    value = cursors[i];\n\n    // For each field in the orderings, the condition is either\n    // a) lt|gt the cursor value,\n    // b) or equal the cursor value and lt|gt the cursor values for other fields\n    condition = or(\n      filterFunc(field, value),\n      and(field.equal(value), condition)\n    );\n  }\n\n  return condition;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError, vector } from '../api';\nimport {\n  _constant,\n  AggregateFunction,\n  AliasedAggregate,\n  array,\n  constant,\n  Expression,\n  AliasedExpression,\n  field,\n  Field,\n  map,\n  Selectable,\n  pipelineValue\n} from '../lite-api/expressions';\nimport type { Pipeline } from '../lite-api/pipeline';\nimport { VectorValue } from '../lite-api/vector_value';\n\nimport { fail } from './assert';\nimport { isPlainObject } from './input_validation';\nimport { isFirestoreValue } from './proto';\nimport { isString } from './types';\n\n/**\n * @deprecated use selectablesToObject instead\n * @param selectables\n */\nexport function selectablesToMap(\n  selectables: Array<Selectable | string>\n): Map<string, Expression> {\n  return new Map(Object.entries(selectablesToObject(selectables)));\n}\n\nexport function selectablesToObject(\n  selectables: Array<Selectable | string>\n): Record<string, Expression> {\n  const result: Record<string, Expression> = {};\n  for (const selectable of selectables) {\n    let alias: string;\n    let expression: Expression;\n    if (typeof selectable === 'string') {\n      alias = selectable as string;\n      expression = field(selectable);\n    } else if (selectable instanceof Field) {\n      alias = selectable.alias;\n      expression = selectable.expr;\n    } else if (selectable instanceof AliasedExpression) {\n      alias = selectable.alias;\n      expression = selectable.expr;\n    } else {\n      fail(0x5319, '`selectable` has an unsupported type', { selectable });\n    }\n\n    if (result[alias] !== undefined) {\n      throw new FirestoreError(\n        'invalid-argument',\n        `Duplicate alias or field '${alias}'`\n      );\n    }\n\n    result[alias] = expression;\n  }\n  return result;\n}\n\nexport function aliasedAggregateToMap(\n  aliasedAggregatees: AliasedAggregate[]\n): Map<string, AggregateFunction> {\n  return aliasedAggregatees.reduce(\n    (map: Map<string, AggregateFunction>, selectable: AliasedAggregate) => {\n      if (map.get(selectable.alias) !== undefined) {\n        throw new FirestoreError(\n          'invalid-argument',\n          `Duplicate alias or field '${selectable.alias}'`\n        );\n      }\n\n      map.set(selectable.alias, selectable.aggregate as AggregateFunction);\n      return map;\n    },\n    new Map() as Map<string, AggregateFunction>\n  );\n}\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n *\n * @private\n * @internal\n * @param value\n */\nexport function vectorToExpr(\n  value: VectorValue | number[] | Expression\n): Expression {\n  if (value instanceof Expression) {\n    return value;\n  } else if (value instanceof VectorValue) {\n    const result = constant(value);\n    return result;\n  } else if (Array.isArray(value)) {\n    const result = constant(vector(value));\n    return result;\n  } else {\n    throw new Error('Unsupported value: ' + typeof value);\n  }\n}\n\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n * If the input is a string, it is assumed to be a field name, and a\n * field(value) is returned.\n *\n * @private\n * @internal\n * @param value\n */\nexport function fieldOrExpression(value: unknown): Expression {\n  if (isString(value)) {\n    const result = field(value);\n    return result;\n  } else {\n    return valueToDefaultExpr(value);\n  }\n}\n/**\n * Converts a value to an Expression, Returning either a Constant, MapFunction,\n * ArrayFunction, or the input itself (if it's already an expression).\n *\n * @private\n * @internal\n * @param value\n */\nexport function valueToDefaultExpr(value: unknown): Expression {\n  let result: Expression | undefined;\n  if (isFirestoreValue(value)) {\n    return constant(value);\n  }\n  if (value instanceof Expression) {\n    return value;\n  } else if (isPlainObject(value)) {\n    result = map(value as Record<string, unknown>);\n  } else if (value instanceof Array) {\n    result = array(value);\n  } else if (isPipeline(value)) {\n    result = pipelineValue(value);\n  } else {\n    result = _constant(value, undefined);\n  }\n\n  return result;\n}\n\n/**\n * Checks if a value is a Pipeline object.\n *\n * We use duck typing here to avoid a circular dependency between pipeline.ts and pipeline_util.ts.\n */\nfunction isPipeline(value: unknown): value is Pipeline {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    typeof (value as Pipeline).toArrayExpression === 'function'\n  );\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { OptionsUtil } from '../core/options_util';\nimport {\n  ApiClientObjectMap,\n  firestoreV1ApiClientInterfaces,\n  Stage as ProtoStage\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n  JsonProtoSerializer,\n  ProtoSerializable,\n  toMapValue,\n  toPipelineValue,\n  toStringValue\n} from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\n\nimport {\n  AggregateFunction,\n  BooleanExpression,\n  Expression,\n  Field,\n  field,\n  Ordering\n} from './expressions';\nimport { Pipeline } from './pipeline';\nimport { QueryEnhancement, StageOptions } from './stage_options';\nimport { isUserData, UserData } from './user_data_reader';\n\nexport abstract class Stage implements ProtoSerializable<ProtoStage>, UserData {\n  /**\n   * Store _optionsProto parsed by _readUserData.\n   * @private\n   * @internal\n   * @protected\n   */\n  protected optionsProto:\n    | ApiClientObjectMap<firestoreV1ApiClientInterfaces.Value>\n    | undefined = undefined;\n  protected knownOptions: Record<string, unknown>;\n  protected rawOptions?: Record<string, unknown>;\n\n  constructor(options: Record<string, unknown> & StageOptions) {\n    ({ rawOptions: this.rawOptions, ...this.knownOptions } = options);\n  }\n\n  _readUserData(context: ParseContext): void {\n    this.optionsProto = this._optionsUtil.getOptionsProto(\n      context,\n      this.knownOptions,\n      this.rawOptions\n    );\n  }\n\n  _toProto(_: JsonProtoSerializer): ProtoStage {\n    return {\n      name: this._name,\n      options: this.optionsProto\n    };\n  }\n\n  abstract get _optionsUtil(): OptionsUtil;\n  abstract get _name(): string;\n}\n\nexport class AddFields extends Stage {\n  get _name(): string {\n    return 'add_fields';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private fields: Map<string, Expression>, options: StageOptions) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.fields)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.fields, context);\n  }\n}\n\nexport class RemoveFields extends Stage {\n  get _name(): string {\n    return 'remove_fields';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private fields: Field[], options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: this.fields.map(f => f._toProto(serializer))\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.fields, context);\n  }\n}\n\n/**\n * @public\n */\nexport class Define extends Stage {\n  get _name(): string {\n    return 'let';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private aliasedExpressions: Map<string, Expression>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.aliasedExpressions)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.aliasedExpressions, context);\n  }\n}\n\nexport class Aggregate extends Stage {\n  get _name(): string {\n    return 'aggregate';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private groups: Map<string, Expression>,\n    private accumulators: Map<string, AggregateFunction>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [\n        toMapValue(serializer, this.accumulators),\n        toMapValue(serializer, this.groups)\n      ]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.groups, context);\n    readUserDataHelper(this.accumulators, context);\n  }\n}\n\nexport class Distinct extends Stage {\n  get _name(): string {\n    return 'distinct';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private groups: Map<string, Expression>, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.groups)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.groups, context);\n  }\n}\n\nexport class CollectionSource extends Stage {\n  get _name(): string {\n    return 'collection';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      forceIndex: {\n        serverName: 'force_index'\n      }\n    });\n  }\n\n  private formattedCollectionPath: string;\n\n  constructor(collection: string, options: StageOptions) {\n    super(options);\n\n    // prepend slash to collection string\n    this.formattedCollectionPath = collection.startsWith('/')\n      ? collection\n      : '/' + collection;\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [{ referenceValue: this.formattedCollectionPath }]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class CollectionGroupSource extends Stage {\n  get _name(): string {\n    return 'collection_group';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      forceIndex: {\n        serverName: 'force_index'\n      }\n    });\n  }\n\n  constructor(private collectionId: string, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [{ referenceValue: '' }, { stringValue: this.collectionId }]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class SubcollectionSource extends Stage {\n  get _name(): string {\n    return 'subcollection';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private path: string, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [{ stringValue: this.path }]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class DatabaseSource extends Stage {\n  get _name(): string {\n    return 'database';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer)\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class DocumentsSource extends Stage {\n  get _name(): string {\n    return 'documents';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  private formattedPaths: string[];\n\n  constructor(docPaths: string[], options: StageOptions) {\n    super(options);\n    this.formattedPaths = docPaths.map(path =>\n      path.startsWith('/') ? path : '/' + path\n    );\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: this.formattedPaths.map(p => {\n        return { referenceValue: p };\n      })\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class Where extends Stage {\n  get _name(): string {\n    return 'where';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private condition: BooleanExpression, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [this.condition._toProto(serializer)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.condition, context);\n  }\n}\n\nexport class FindNearest extends Stage {\n  get _name(): string {\n    return 'find_nearest';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      limit: {\n        serverName: 'limit'\n      },\n      distanceField: {\n        serverName: 'distance_field'\n      }\n    });\n  }\n\n  constructor(\n    private vectorValue: Expression,\n    private field: Field,\n    private distanceMeasure: 'euclidean' | 'cosine' | 'dot_product',\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [\n        this.field._toProto(serializer),\n        this.vectorValue._toProto(serializer),\n        toStringValue(this.distanceMeasure)\n      ]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.vectorValue, context);\n    readUserDataHelper(this.field, context);\n  }\n}\n\nexport class Limit extends Stage {\n  get _name(): string {\n    return 'limit';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private limit: number, options: StageOptions) {\n    hardAssert(\n      !isNaN(limit) && limit !== Infinity && limit !== -Infinity,\n      0x882c,\n      'Invalid limit value'\n    );\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toNumber(serializer, this.limit)]\n    };\n  }\n}\n\nexport class Offset extends Stage {\n  get _name(): string {\n    return 'offset';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private offset: number, options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toNumber(serializer, this.offset)]\n    };\n  }\n}\n\nexport class Select extends Stage {\n  get _name(): string {\n    return 'select';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private selections: Map<string, Expression>,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toMapValue(serializer, this.selections)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.selections, context);\n  }\n}\n\nexport class Sort extends Stage {\n  get _name(): string {\n    return 'sort';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private orderings: Ordering[], options: StageOptions) {\n    super(options);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: this.orderings.map(o => o._toProto(serializer))\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.orderings, context);\n  }\n}\n\nexport class Sample extends Stage {\n  get _name(): string {\n    return 'sample';\n  }\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(\n    private rate: number,\n    private mode: 'percent' | 'documents',\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toNumber(serializer, this.rate)!, toStringValue(this.mode)!]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n  }\n}\n\nexport class Union extends Stage {\n  get _name(): string {\n    return 'union';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private other: Pipeline, options: StageOptions) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [toPipelineValue(this.other._toProto(serializer))]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    this.other._readUserData(context);\n    super._readUserData(context);\n  }\n}\n\nexport class Unnest extends Stage {\n  get _name(): string {\n    return 'unnest';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      indexField: {\n        serverName: 'index_field'\n      }\n    });\n  }\n\n  constructor(\n    private alias: string,\n    private expr: Expression,\n    options: StageOptions\n  ) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [\n        this.expr._toProto(serializer),\n        field(this.alias)._toProto(serializer)\n      ]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.expr, context);\n  }\n}\n\nexport class Replace extends Stage {\n  static readonly MODE = 'full_replace';\n\n  get _name(): string {\n    return 'replace_with';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n\n  constructor(private map: Expression, options: StageOptions) {\n    super(options);\n  }\n\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: [this.map._toProto(serializer), toStringValue(Replace.MODE)]\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.map, context);\n  }\n}\n\n// eslint-disable-next-line -- eslint should not convert this type to an interface\ntype InternalSearchOptions = {\n  // These are constrained from the public type\n  query: BooleanExpression;\n  sort?: Ordering[];\n  select?: Record<string, Expression>;\n  addFields?: Record<string, Expression>;\n\n  // These are the same as the public type\n  languageCode?: string;\n  retrievalDepth?: number;\n  offset?: number;\n  limit?: number;\n  queryEnhancement?: QueryEnhancement;\n};\n\n/**\n * @beta\n */\nexport class Search extends Stage {\n  constructor(private _searchOptions: InternalSearchOptions) {\n    super(_searchOptions);\n  }\n\n  get _name(): string {\n    return 'search';\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({\n      query: {\n        serverName: 'query'\n      },\n      limit: {\n        serverName: 'limit'\n      },\n      retrievalDepth: {\n        serverName: 'retrieval_depth'\n      },\n      sort: {\n        serverName: 'sort'\n      },\n      addFields: {\n        serverName: 'add_fields'\n      },\n      select: {\n        serverName: 'select'\n      },\n      offset: {\n        serverName: 'offset'\n      },\n      queryEnhancement: {\n        serverName: 'query_enhancement'\n      },\n      languageCode: {\n        serverName: 'language_code'\n      }\n    });\n  }\n\n  /**\n   * @private\n   * @internal\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      ...super._toProto(serializer),\n      args: []\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    readUserDataHelper(this._searchOptions.query, context);\n    if (this._searchOptions.addFields) {\n      readUserDataHelper(this._searchOptions.addFields, context);\n    }\n    if (this._searchOptions.select) {\n      readUserDataHelper(this._searchOptions.select, context);\n    }\n    if (this._searchOptions.sort) {\n      readUserDataHelper(this._searchOptions.sort, context);\n    }\n\n    super._readUserData(context);\n  }\n}\n\n/**\n * @beta\n */\nexport class RawStage extends Stage {\n  /**\n   * @private\n   * @internal\n   */\n  constructor(\n    private name: string,\n    private params: Array<AggregateFunction | Expression>,\n    rawOptions: Record<string, unknown>\n  ) {\n    super({ rawOptions });\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(serializer: JsonProtoSerializer): ProtoStage {\n    return {\n      name: this.name,\n      args: this.params.map(o => o._toProto(serializer)),\n      options: this.optionsProto\n    };\n  }\n\n  _readUserData(context: ParseContext): void {\n    super._readUserData(context);\n    readUserDataHelper(this.params, context);\n  }\n\n  get _name(): string {\n    return this.name;\n  }\n\n  get _optionsUtil(): OptionsUtil {\n    return new OptionsUtil({});\n  }\n}\n\n/**\n * Helper to read user data across a number of different formats.\n * @param name - Name of the calling function. Used for error messages when invalid user data is encountered.\n * @param expressionMap\n * @returns the expressionMap argument.\n * @private\n */\nfunction readUserDataHelper<\n  T extends\n    | Map<string, UserData>\n    | Record<string, UserData>\n    | UserData[]\n    | UserData\n>(expressionMap: T, context: ParseContext): T {\n  if (isUserData(expressionMap)) {\n    expressionMap._readUserData(context);\n  } else if (Array.isArray(expressionMap)) {\n    expressionMap.forEach(readableData => readableData._readUserData(context));\n  } else if (expressionMap instanceof Map) {\n    expressionMap.forEach(expr => expr._readUserData(context));\n  } else {\n    Object.values(expressionMap).forEach(expression =>\n      expression._readUserData(context)\n    );\n  }\n  return expressionMap;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport {\n  Pipeline as ProtoPipeline,\n  Stage as ProtoStage\n} from '../protos/firestore_proto_api';\nimport { JsonProtoSerializer, ProtoSerializable } from '../remote/serializer';\nimport { isPlainObject } from '../util/input_validation';\nimport {\n  aliasedAggregateToMap,\n  fieldOrExpression,\n  selectablesToMap,\n  selectablesToObject,\n  vectorToExpr\n} from '../util/pipeline_util';\nimport { isNumber, isString } from '../util/types';\n\nimport { Firestore } from './database';\nimport {\n  _mapValue,\n  AggregateFunction,\n  AliasedAggregate,\n  BooleanExpression,\n  _constant,\n  Expression,\n  Field,\n  field,\n  Ordering,\n  Selectable,\n  _field,\n  isSelectable,\n  isField,\n  isBooleanExpr,\n  isAliasedAggregate,\n  toField,\n  isOrdering,\n  isExpr,\n  AliasedExpression,\n  FunctionExpression,\n  isAliasedExpr,\n  documentMatches\n} from './expressions';\nimport {\n  AddFields,\n  Aggregate,\n  Distinct,\n  FindNearest,\n  RawStage,\n  Limit,\n  Offset,\n  RemoveFields,\n  Replace,\n  Sample,\n  Select,\n  Sort,\n  Stage,\n  Union,\n  Unnest,\n  Where,\n  Define,\n  Search\n} from './stage';\nimport {\n  AddFieldsStageOptions,\n  AggregateStageOptions,\n  DefineStageOptions,\n  DistinctStageOptions,\n  FindNearestStageOptions,\n  LimitStageOptions,\n  OffsetStageOptions,\n  RemoveFieldsStageOptions,\n  ReplaceWithStageOptions,\n  SampleStageOptions,\n  SearchStageOptions,\n  SelectStageOptions,\n  SortStageOptions,\n  StageOptions,\n  UnionStageOptions,\n  UnnestStageOptions,\n  WhereStageOptions\n} from './stage_options';\nimport { UserData } from './user_data_reader';\n\n/**\n *\n * The Pipeline class provides a flexible and expressive framework for building complex data\n * transformation and query pipelines for Firestore.\n *\n * A pipeline takes data sources, such as Firestore collections or collection groups, and applies\n * a series of stages that are chained together. Each stage takes the output from the previous stage\n * (or the data source) and produces an output for the next stage (or as the final output of the\n * pipeline).\n *\n * Expressions can be used within each stage to filter and transform data through the stage.\n *\n * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline.\n * Instead, Firestore only guarantees that the result is the same as if the chained stages were\n * executed in order.\n *\n * Usage Examples:\n *\n * @example\n * ```typescript\n * const db: Firestore; // Assumes a valid firestore instance.\n *\n * // Example 1: Select specific fields and rename 'rating' to 'bookRating'\n * const results1 = await execute(db.pipeline()\n *     .collection(\"books\")\n *     .select(\"title\", \"author\", field(\"rating\").as(\"bookRating\")));\n *\n * // Example 2: Filter documents where 'genre' is \"Science Fiction\" and 'published' is after 1950\n * const results2 = await execute(db.pipeline()\n *     .collection(\"books\")\n *     .where(and(field(\"genre\").equal(\"Science Fiction\"), field(\"published\").greaterThan(1950))));\n *\n * // Example 3: Calculate the average rating of books published after 1980\n * const results3 = await execute(db.pipeline()\n *     .collection(\"books\")\n *     .where(field(\"published\").greaterThan(1980))\n *     .aggregate(average(field(\"rating\")).as(\"averageRating\")));\n * ```\n */\nexport class Pipeline implements ProtoSerializable<ProtoPipeline>, UserData {\n  /**\n   * @internal\n   * @private\n   * @param _db\n   * @param stages\n   */\n  constructor(\n    /**\n     * @internal\n     * @private\n     */\n    public _db: Firestore | undefined,\n    /**\n     * @internal\n     * @private\n     */\n    private stages: Stage[]\n  ) {}\n\n  _readUserData(context: ParseContext): void {\n    this.stages.forEach(stage => {\n      const subContext = context.contextWith({\n        methodName: stage._name\n      });\n      stage._readUserData(subContext);\n    });\n  }\n\n  /**\n   * Adds new fields to outputs from previous stages.\n   *\n   * This stage allows you to compute values on-the-fly based on existing data from previous\n   * stages or constants. You can use this to create new fields or overwrite existing ones (if there\n   * is name overlaps).\n   *\n   * The added fields are defined using {@link @firebase/firestore/pipelines#Selectable}s, which can be:\n   *\n   * - {@link @firebase/firestore/pipelines#Field}: References an existing document field.\n   * - {@link @firebase/firestore/pipelines#Expression}: Either a literal value (see {@link @firebase/firestore/pipelines#(constant:1)}) or a computed value\n   *   with an assigned alias using {@link @firebase/firestore/pipelines#Expression.(as:1)}.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * firestore.pipeline().collection(\"books\")\n   *   .addFields(\n   *     field(\"rating\").as(\"bookRating\"), // Rename 'rating' to 'bookRating'\n   *     add(field(\"quantity\"), 5).as(\"totalCost\")  // Calculate 'totalCost'\n   *   );\n   * ```\n   *\n   * @param field - The first field to add to the documents, specified as a {@link @firebase/firestore/pipelines#Selectable}.\n   * @param additionalFields - Optional additional fields to add to the documents, specified as {@link @firebase/firestore/pipelines#Selectable}s.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline;\n  /**\n   * Adds new fields to outputs from previous stages.\n   *\n   * This stage allows you to compute values on-the-fly based on existing data from previous\n   * stages or constants. You can use this to create new fields or overwrite existing ones (if there\n   * is name overlaps).\n   *\n   * The added fields are defined using {@link @firebase/firestore/pipelines#Selectable}s, which can be:\n   *\n   * - {@link @firebase/firestore/pipelines#Field}: References an existing document field.\n   * - {@link @firebase/firestore/pipelines#Expression}: Either a literal value (see {@link @firebase/firestore/pipelines#(constant:1)}) or a computed value\n   *   with an assigned alias using {@link @firebase/firestore/pipelines#Expression.(as:1)}.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * firestore.pipeline().collection(\"books\")\n   *   .addFields(\n   *     field(\"rating\").as(\"bookRating\"), // Rename 'rating' to 'bookRating'\n   *     add(field(\"quantity\"), 5).as(\"totalCost\")  // Calculate 'totalCost'\n   *   );\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  addFields(options: AddFieldsStageOptions): Pipeline;\n  addFields(\n    fieldOrOptions: Selectable | AddFieldsStageOptions,\n    ...additionalFields: Selectable[]\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    let fields: Selectable[];\n    let options: {};\n    if (isSelectable(fieldOrOptions)) {\n      fields = [fieldOrOptions, ...additionalFields];\n      options = {};\n    } else {\n      ({ fields, ...options } = fieldOrOptions);\n    }\n\n    // Convert user land convenience types to internal types\n    const normalizedFields: Map<string, Expression> = selectablesToMap(fields);\n\n    // Create stage object\n    const stage = new AddFields(normalizedFields, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Remove fields from outputs of previous stages.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * firestore.pipeline().collection('books')\n   *   // removes field 'rating' and 'cost' from the previous stage outputs.\n   *   .removeFields(\n   *     field('rating'),\n   *     'cost'\n   *   );\n   * ```\n   *\n   * @param fieldValue - The first field to remove.\n   * @param additionalFields - Optional additional fields to remove.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  removeFields(\n    fieldValue: Field | string,\n    ...additionalFields: Array<Field | string>\n  ): Pipeline;\n  /**\n   * Remove fields from outputs of previous stages.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * firestore.pipeline().collection('books')\n   *   // removes field 'rating' and 'cost' from the previous stage outputs.\n   *   .removeFields(\n   *     field('rating'),\n   *     'cost'\n   *   );\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  removeFields(options: RemoveFieldsStageOptions): Pipeline;\n  removeFields(\n    fieldValueOrOptions: Field | string | RemoveFieldsStageOptions,\n    ...additionalFields: Array<Field | string>\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options =\n      isField(fieldValueOrOptions) || isString(fieldValueOrOptions)\n        ? {}\n        : fieldValueOrOptions;\n    const fields: Array<Field | string> =\n      isField(fieldValueOrOptions) || isString(fieldValueOrOptions)\n        ? [fieldValueOrOptions, ...additionalFields]\n        : fieldValueOrOptions.fields;\n\n    // Convert user land convenience types to internal types\n    const convertedFields: Field[] = fields.map(f =>\n      isString(f) ? field(f) : (f as Field)\n    );\n\n    // Create stage object\n    const stage = new RemoveFields(convertedFields, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * @public\n   * Defines one or more variables in the pipeline's scope. `define` is used to bind a value to a\n   * variable for internal reuse within the pipeline body (accessed via the `variable()` function).\n   *\n   * This stage is useful for declaring reusable values or intermediate calculations that can be\n   * referenced multiple times in later parts of the pipeline, improving readability and\n   * maintainability.\n   *\n   * Each variable is defined using an {@link @firebase/firestore/pipelines#AliasedExpression}, which pairs an expression with a name\n   * (alias). The expression can be a simple constant, a field reference, or a complex computation.\n   *\n   * @example\n   * ```typescript\n   * db.pipeline().collection(\"products\")\n   *   .define(\n   *     field(\"price\").multiply(0.9).as(\"discountedPrice\"),\n   *     field(\"stock\").add(10).as(\"newStock\")\n   *   )\n   *   .where(variable(\"discountedPrice\").lessThan(100))\n   *   .select(field(\"name\"), variable(\"newStock\"));\n   * ```\n   *\n   * @param aliasedExpression - The first expression to bind to a variable.\n   * @param additionalExpressions - Optional additional expression to bind to a variable.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  define(\n    aliasedExpression: AliasedExpression,\n    ...additionalExpressions: AliasedExpression[]\n  ): Pipeline;\n  /**\n   * @public\n   * Defines one or more variables in the pipeline's scope. `define` is used to bind a value to a\n   * variable for internal reuse within the pipeline body (accessed via the `variable()` function).\n   *\n   * This stage is useful for declaring reusable values or intermediate calculations that can be\n   * referenced multiple times in later parts of the pipeline, improving readability and\n   * maintainability.\n   *\n   * Each variable is defined using an {@link @firebase/firestore/pipelines#AliasedExpression}, which pairs an expression with a name\n   * (alias). The expression can be a simple constant, a field reference, or a complex computation.\n   *\n   * @example\n   * ```typescript\n   * db.pipeline().collection(\"products\")\n   *   .define(\n   *     field(\"price\").multiply(0.9).as(\"discountedPrice\"),\n   *     field(\"stock\").add(10).as(\"newStock\")\n   *   )\n   *   .where(variable(\"discountedPrice\").lessThan(100))\n   *   .select(field(\"name\"), variable(\"newStock\"));\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  define(options: DefineStageOptions): Pipeline;\n  define(\n    aliasedExpressionOrOptions: AliasedExpression | DefineStageOptions,\n    ...additionalExpressions: AliasedExpression[]\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options = isAliasedExpr(aliasedExpressionOrOptions)\n      ? {}\n      : aliasedExpressionOrOptions;\n    const aliasedExpressions: AliasedExpression[] = isAliasedExpr(\n      aliasedExpressionOrOptions\n    )\n      ? [aliasedExpressionOrOptions, ...additionalExpressions]\n      : aliasedExpressionOrOptions.variables;\n\n    const convertedExpressions: Map<string, Expression> =\n      selectablesToMap(aliasedExpressions);\n\n    const stage = new Define(convertedExpressions, options);\n\n    return this._addStage(stage);\n  }\n\n  /**\n   * @public\n   * Converts this Pipeline into an expression that evaluates to an array of results.\n   *\n   * <p>Result Unwrapping:</p>\n   * <ul>\n   *  <li>If the items have a single field, their values are unwrapped and returned directly in the array.</li>\n   *  <li>If the items have multiple fields, they are returned as objects in the array</li>\n   * </ul>\n   *\n   * @example\n   * ```typescript\n   * // Get a list of reviewers for each book\n   * db.pipeline().collection(\"books\")\n   *     .define(field(\"id\").as(\"book_id\"))\n   *     .addFields(\n   *         db.pipeline().collection(\"reviews\")\n   *             .where(field(\"book_id\").equal(variable(\"book_id\")))\n   *             .select(field(\"reviewer\"))\n   *             .toArrayExpression()\n   *             .as(\"reviewers\")\n   *     )\n   * ```\n   *\n   * Output:\n   * ```json\n   * [\n   *   {\n   *     \"id\": \"1\",\n   *     \"title\": \"1984\",\n   *     \"reviewers\": [\"Alice\", \"Bob\"]\n   *   }\n   * ]\n   * ```\n   *\n   * Multiple Fields:\n   * ```typescript\n   * // Get a list of reviews (reviewer and rating) for each book\n   * db.pipeline().collection(\"books\")\n   *     .define(field(\"id\").as(\"book_id\"))\n   *     .addFields(\n   *         db.pipeline().collection(\"reviews\")\n   *             .where(field(\"book_id\").equal(variable(\"book_id\")))\n   *             .select(field(\"reviewer\"), field(\"rating\"))\n   *             .toArrayExpression()\n   *             .as(\"reviews\"))\n   * ```\n   *\n   * Output:\n   * ```json\n   * [\n   *   {\n   *     \"id\": \"1\",\n   *     \"title\": \"1984\",\n   *     \"reviews\": [\n   *       { \"reviewer\": \"Alice\", \"rating\": 5 },\n   *       { \"reviewer\": \"Bob\", \"rating\": 4 }\n   *     ]\n   *   }\n   * ]\n   * ```\n   *\n   * @returns An `Expression` representing the execution of this pipeline.\n   */\n  toArrayExpression(): Expression {\n    return new FunctionExpression('array', [fieldOrExpression(this)]);\n  }\n\n  /**\n   * @public\n   * Converts this Pipeline into an expression that evaluates to a single scalar result.\n   *\n   * <p><b>Runtime Validation:</b> The runtime validates that the result set contains zero or one item. If\n   * zero items, it evaluates to `null`.</p>\n   *\n   * <p>Result Unwrapping:</p>\n   * <ul>\n   *  <li>If the item has a single field, its value is unwrapped and returned directly.</li>\n   *  <li>f the item has multiple fields, they are returned as an object.</li>\n   * </ul>\n   *\n   * @example\n   * ```typescript\n   * // Calculate average rating for a restaurant\n   * db.pipeline().collection(\"restaurants\").addFields(\n   *   db.pipeline().collection(\"reviews\")\n   *     .where(field(\"restaurant_id\").equal(variable(\"rid\")))\n   *     .aggregate(average(\"rating\").as(\"avg\"))\n   *     // Unwraps the single \"avg\" field to a scalar double\n   *     .toScalarExpression().as(\"average_rating\")\n   * )\n   * ```\n   *\n   * Output:\n   * ```json\n   * {\n   *   \"name\": \"The Burger Joint\",\n   *   \"average_rating\": 4.5\n   * }\n   * ```\n   *\n   * Multiple Fields:\n   * ```typescript\n   * // Calculate average rating AND count for a restaurant\n   * db.pipeline().collection(\"restaurants\").addFields(\n   *   db.pipeline().collection(\"reviews\")\n   *     .where(field(\"restaurant_id\").equal(variable(\"rid\")))\n   *     .aggregate(\n   *       average(\"rating\").as(\"avg\"),\n   *       count().as(\"count\")\n   *     )\n   *     // Returns an object with \"avg\" and \"count\" fields\n   *     .toScalarExpression().as(\"stats\")\n   * )\n   * ```\n   *\n   * Output:\n   * ```json\n   * {\n   *   \"name\": \"The Burger Joint\",\n   *   \"stats\": {\n   *     \"avg\": 4.5,\n   *     \"count\": 100\n   *   }\n   * }\n   * ```\n   *\n   * @returns An `Expression` representing the execution of this pipeline.\n   */\n  toScalarExpression(): Expression {\n    return new FunctionExpression('scalar', [fieldOrExpression(this)]);\n  }\n\n  /**\n   * Selects or creates a set of fields from the outputs of previous stages.\n   *\n   * <p>The selected fields are defined using {@link @firebase/firestore/pipelines#Selectable} expressions, which can be:\n   *\n   * <ul>\n   *   <li>`string` : Name of an existing field</li>\n   *   <li>{@link @firebase/firestore/pipelines#Field}: References an existing field.</li>\n   *   <li>{@link @firebase/firestore/pipelines#AliasedExpression}: Represents the result of a function with an assigned alias name using\n   *       {@link @firebase/firestore/pipelines#Expression.(as:1)}</li>\n   * </ul>\n   *\n   * <p>If no selections are provided, the output of this stage is empty. Use {@link\n   * @firebase/firestore/pipelines#Pipeline.(addFields:1)} instead if only additions are\n   * desired.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * db.pipeline().collection(\"books\")\n   *   .select(\n   *     \"firstName\",\n   *     field(\"lastName\"),\n   *     field(\"address\").toUpper().as(\"upperAddress\"),\n   *   );\n   * ```\n   *\n   * @param selection - The first field to include in the output documents, specified as {@link\n   *     @firebase/firestore/pipelines#Selectable} expression or string value representing the field name.\n   * @param additionalSelections - Optional additional fields to include in the output documents, specified as {@link\n   *     @firebase/firestore/pipelines#Selectable} expressions or `string` values representing field names.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  select(\n    selection: Selectable | string,\n    ...additionalSelections: Array<Selectable | string>\n  ): Pipeline;\n  /**\n   * Selects or creates a set of fields from the outputs of previous stages.\n   *\n   * <p>The selected fields are defined using {@link @firebase/firestore/pipelines#Selectable} expressions, which can be:\n   *\n   * <ul>\n   *   <li>`string`: Name of an existing field</li>\n   *   <li>{@link @firebase/firestore/pipelines#Field}: References an existing field.</li>\n   *   <li>{@link @firebase/firestore/pipelines#AliasedExpression}: Represents the result of a function with an assigned alias name using\n   *       {@link @firebase/firestore/pipelines#Expression.(as:1)}</li>\n   * </ul>\n   *\n   * <p>If no selections are provided, the output of this stage is empty. Use {@link\n   * @firebase/firestore/pipelines#Pipeline.(addFields:1)} instead if only additions are\n   * desired.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * db.pipeline().collection(\"books\")\n   *   .select(\n   *     \"firstName\",\n   *     field(\"lastName\"),\n   *     field(\"address\").toUpper().as(\"upperAddress\"),\n   *   );\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  select(options: SelectStageOptions): Pipeline;\n  select(\n    selectionOrOptions: Selectable | string | SelectStageOptions,\n    ...additionalSelections: Array<Selectable | string>\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options =\n      isSelectable(selectionOrOptions) || isString(selectionOrOptions)\n        ? {}\n        : selectionOrOptions;\n\n    const selections: Array<Selectable | string> =\n      isSelectable(selectionOrOptions) || isString(selectionOrOptions)\n        ? [selectionOrOptions, ...additionalSelections]\n        : selectionOrOptions.selections;\n\n    // Convert user land convenience types to internal types\n    const normalizedSelections: Map<string, Expression> =\n      selectablesToMap(selections);\n\n    // Create stage object\n    const stage = new Select(normalizedSelections, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Filters the documents from previous stages to only include those matching the specified {@link\n   * @firebase/firestore/pipelines#BooleanExpression}.\n   *\n   * <p>This stage allows you to apply conditions to the data, similar to a \"WHERE\" clause in SQL.\n   * You can filter documents based on their field values, using implementations of {@link\n   * @firebase/firestore/pipelines#BooleanExpression}, typically including but not limited to:\n   *\n   * <ul>\n   *   <li>field comparators: {@link @firebase/firestore/pipelines#Expression.(equal:1)}, {@link @firebase/firestore/pipelines#Expression.(lessThan:1)}, {@link\n   *       @firebase/firestore/pipelines#Expression.(greaterThan:1)}, etc.</li>\n   *   <li>logical operators: {@link @firebase/firestore/pipelines#Expression.(and:1)}, {@link @firebase/firestore/pipelines#Expression.(or:1)}, {@link @firebase/firestore/pipelines#Expression.(not:1)}, etc.</li>\n   *   <li>advanced functions: {@link @firebase/firestore/pipelines#Expression.(regexMatch:1)}, {@link\n   *       @firebase/firestore/pipelines#Expression.(arrayContains:1)}, etc.</li>\n   * </ul>\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * firestore.pipeline().collection(\"books\")\n   *   .where(\n   *     and(\n   *         greaterThan(field(\"rating\"), 4.0),   // Filter for ratings greater than 4.0\n   *         field(\"genre\").equal(\"Science Fiction\") // Equivalent to equal(\"genre\", \"Science Fiction\")\n   *     )\n   *   );\n   * ```\n   *\n   * @param condition - The {@link @firebase/firestore/pipelines#BooleanExpression} to apply.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  where(condition: BooleanExpression): Pipeline;\n  /**\n   * Filters the documents from previous stages to only include those matching the specified {@link\n   * @firebase/firestore/pipelines#BooleanExpression}.\n   *\n   * <p>This stage allows you to apply conditions to the data, similar to a \"WHERE\" clause in SQL.\n   * You can filter documents based on their field values, using implementations of {@link\n   * @firebase/firestore/pipelines#BooleanExpression}, typically including but not limited to:\n   *\n   * <ul>\n   *   <li>field comparators: {@link @firebase/firestore/pipelines#Expression.(eq:1)}, {@link @firebase/firestore/pipelines#Expression.(lt:1)} (less than), {@link\n   *       @firebase/firestore/pipelines#Expression.(greaterThan:1)}, etc.</li>\n   *   <li>logical operators: {@link @firebase/firestore/pipelines#Expression.(and:1)}, {@link @firebase/firestore/pipelines#Expression.(or:1)}, {@link @firebase/firestore/pipelines#Expression.(not:1)}, etc.</li>\n   *   <li>advanced functions: {@link @firebase/firestore/pipelines#Expression.(regexMatch:1)}, {@link\n   *       @firebase/firestore/pipelines#Expression.(arrayContains:1)}, etc.</li>\n   * </ul>\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * firestore.pipeline().collection(\"books\")\n   *   .where(\n   *     and(\n   *         greaterThan(field(\"rating\"), 4.0),   // Filter for ratings greater than 4.0\n   *         field(\"genre\").equal(\"Science Fiction\") // Equivalent to equal(\"genre\", \"Science Fiction\")\n   *     )\n   *   );\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  where(options: WhereStageOptions): Pipeline;\n  where(conditionOrOptions: BooleanExpression | WhereStageOptions): Pipeline {\n    // Process argument union(s) from method overloads\n    const options = isBooleanExpr(conditionOrOptions) ? {} : conditionOrOptions;\n    const condition: BooleanExpression = isBooleanExpr(conditionOrOptions)\n      ? conditionOrOptions\n      : conditionOrOptions.condition;\n\n    // Create stage object\n    const stage = new Where(condition, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Skips the first `offset` number of documents from the results of previous stages.\n   *\n   * <p>This stage is useful for implementing pagination in your pipelines, allowing you to retrieve\n   * results in chunks. It is typically used in conjunction with {@link @firebase/firestore/pipelines#Pipeline.limit} to control the\n   * size of each page.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Retrieve the second page of 20 results\n   * firestore.pipeline().collection('books')\n   *     .sort(field('published').descending())\n   *     .offset(20)  // Skip the first 20 results\n   *     .limit(20);   // Take the next 20 results\n   * ```\n   *\n   * @param offset - The number of documents to skip.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  offset(offset: number): Pipeline;\n  /**\n   * Skips the first `offset` number of documents from the results of previous stages.\n   *\n   * <p>This stage is useful for implementing pagination in your pipelines, allowing you to retrieve\n   * results in chunks. It is typically used in conjunction with {@link @firebase/firestore/pipelines#Pipeline.limit} to control the\n   * size of each page.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Retrieve the second page of 20 results\n   * firestore.pipeline().collection('books')\n   *     .sort(field('published').descending())\n   *     .offset(20)  // Skip the first 20 results\n   *     .limit(20);   // Take the next 20 results\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  offset(options: OffsetStageOptions): Pipeline;\n  offset(offsetOrOptions: number | OffsetStageOptions): Pipeline {\n    // Process argument union(s) from method overloads\n    let options: {};\n    let offset: number;\n    if (isNumber(offsetOrOptions)) {\n      options = {};\n      offset = offsetOrOptions;\n    } else {\n      options = offsetOrOptions;\n      offset = offsetOrOptions.offset;\n    }\n\n    // Create stage object\n    const stage = new Offset(offset, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Limits the maximum number of documents returned by previous stages to `limit`.\n   *\n   * <p>This stage is particularly useful when you want to retrieve a controlled subset of data from\n   * a potentially large result set. It's often used for:\n   *\n   * <ul>\n   *   <li>**Pagination:** In combination with {@link @firebase/firestore/pipelines#Pipeline.offset} to retrieve specific pages of\n   *       results.</li>\n   *   <li>**Limiting Data Retrieval:** To prevent excessive data transfer and improve performance,\n   *       especially when dealing with large collections.</li>\n   * </ul>\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Limit the results to the top 10 highest-rated books\n   * firestore.pipeline().collection('books')\n   *     .sort(field('rating').descending())\n   *     .limit(10);\n   * ```\n   *\n   * @param limit - The maximum number of documents to return.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  limit(limit: number): Pipeline;\n  /**\n   * Limits the maximum number of documents returned by previous stages to `limit`.\n   *\n   * <p>This stage is particularly useful when you want to retrieve a controlled subset of data from\n   * a potentially large result set. It's often used for:\n   *\n   * <ul>\n   *   <li>**Pagination:** In combination with {@link @firebase/firestore/pipelines#Pipeline.offset} to retrieve specific pages of\n   *       results.</li>\n   *   <li>**Limiting Data Retrieval:** To prevent excessive data transfer and improve performance,\n   *       especially when dealing with large collections.</li>\n   * </ul>\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Limit the results to the top 10 highest-rated books\n   * firestore.pipeline().collection('books')\n   *     .sort(field('rating').descending())\n   *     .limit(10);\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  limit(options: LimitStageOptions): Pipeline;\n  limit(limitOrOptions: number | LimitStageOptions): Pipeline {\n    // Process argument union(s) from method overloads\n    const options = isNumber(limitOrOptions) ? {} : limitOrOptions;\n    const limit: number = isNumber(limitOrOptions)\n      ? limitOrOptions\n      : limitOrOptions.limit;\n\n    // Create stage object\n    const stage = new Limit(limit, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Returns a set of distinct values from the inputs to this stage.\n   *\n   * This stage runs through the results from previous stages to include only results with\n   * unique combinations of {@link @firebase/firestore/pipelines#Expression} values ({@link @firebase/firestore/pipelines#Field}, {@link @firebase/firestore/pipelines#AliasedExpression}, etc).\n   *\n   * The parameters to this stage are defined using {@link @firebase/firestore/pipelines#Selectable} expressions or strings:\n   *\n   * - `string`: Name of an existing field\n   * - {@link @firebase/firestore/pipelines#Field}: References an existing document field.\n   * - {@link @firebase/firestore/pipelines#AliasedExpression}: Represents the result of a function with an assigned alias name\n   *   using {@link @firebase/firestore/pipelines#Expression.(as:1)}.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * // Get a list of unique author names in uppercase and genre combinations.\n   * firestore.pipeline().collection(\"books\")\n   *     .distinct(toUpper(field(\"author\")).as(\"authorName\"), field(\"genre\"), \"publishedAt\")\n   *     .select(\"authorName\");\n   * ```\n   *\n   * @param group - The {@link @firebase/firestore/pipelines#Selectable} expression or field name to consider when determining\n   *     distinct value combinations.\n   * @param additionalGroups - Optional additional {@link @firebase/firestore/pipelines#Selectable} expressions to consider when determining distinct\n   *     value combinations or strings representing field names.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  distinct(\n    group: string | Selectable,\n    ...additionalGroups: Array<string | Selectable>\n  ): Pipeline;\n  /**\n   * Returns a set of distinct values from the inputs to this stage.\n   *\n   * This stage runs through the results from previous stages to include only results with\n   * unique combinations of {@link @firebase/firestore/pipelines#Expression} values ({@link @firebase/firestore/pipelines#Field}, {@link @firebase/firestore/pipelines#AliasedExpression}, etc).\n   *\n   * The parameters to this stage are defined using {@link @firebase/firestore/pipelines#Selectable} expressions or strings:\n   *\n   * - `string`: Name of an existing field\n   * - {@link @firebase/firestore/pipelines#Field}: References an existing document field.\n   * - {@link @firebase/firestore/pipelines#AliasedExpression}: Represents the result of a function with an assigned alias name\n   *   using {@link @firebase/firestore/pipelines#Expression.(as:1)}.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * // Get a list of unique author names in uppercase and genre combinations.\n   * firestore.pipeline().collection(\"books\")\n   *     .distinct(toUpper(field(\"author\")).as(\"authorName\"), field(\"genre\"), \"publishedAt\")\n   *     .select(\"authorName\");\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  distinct(options: DistinctStageOptions): Pipeline;\n  distinct(\n    groupOrOptions: string | Selectable | DistinctStageOptions,\n    ...additionalGroups: Array<string | Selectable>\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options =\n      isString(groupOrOptions) || isSelectable(groupOrOptions)\n        ? {}\n        : groupOrOptions;\n    const groups: Array<string | Selectable> =\n      isString(groupOrOptions) || isSelectable(groupOrOptions)\n        ? [groupOrOptions, ...additionalGroups]\n        : groupOrOptions.groups;\n\n    // Convert user land convenience types to internal types\n    const convertedGroups: Map<string, Expression> = selectablesToMap(groups);\n\n    // Create stage object\n    const stage = new Distinct(convertedGroups, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Performs aggregation operations on the documents from previous stages.\n   *\n   * <p>This stage allows you to calculate aggregate values over a set of documents. You define the\n   * aggregations to perform using {@link @firebase/firestore/pipelines#AliasedAggregate} expressions which are typically results of\n   * calling {@link @firebase/firestore/pipelines#Expression.(as:1)} on {@link @firebase/firestore/pipelines#AggregateFunction} instances.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Calculate the average rating and the total number of books\n   * firestore.pipeline().collection(\"books\")\n   *     .aggregate(\n   *         field(\"rating\").average().as(\"averageRating\"),\n   *         countAll().as(\"totalBooks\")\n   *     );\n   * ```\n   *\n   * @param accumulator - The first {@link @firebase/firestore/pipelines#AliasedAggregate}, wrapping an {@link @firebase/firestore/pipelines#AggregateFunction}\n   *     and providing a name for the accumulated results.\n   * @param additionalAccumulators - Optional additional {@link @firebase/firestore/pipelines#AliasedAggregate}, each wrapping an {@link @firebase/firestore/pipelines#AggregateFunction}\n   *     and providing a name for the accumulated results.\n   * @returns A new Pipeline object with this stage appended to the stage list.\n   */\n  aggregate(\n    accumulator: AliasedAggregate,\n    ...additionalAccumulators: AliasedAggregate[]\n  ): Pipeline;\n  /**\n   * Performs optionally grouped aggregation operations on the documents from previous stages.\n   *\n   * <p>This stage allows you to calculate aggregate values over a set of documents, optionally\n   * grouped by one or more fields or functions. You can specify:\n   *\n   * <ul>\n   *   <li>**Grouping Fields or Functions:** One or more fields or functions to group the documents\n   *       by. For each distinct combination of values in these fields, a separate group is created.\n   *       If no grouping fields are provided, a single group containing all documents is used. Not\n   *       specifying groups is the same as putting the entire inputs into one group.</li>\n   *   <li>**Accumulators:** One or more accumulation operations to perform within each group. These\n   *       are defined using {@link @firebase/firestore/pipelines#AliasedAggregate} expressions, which are typically created by\n   *       calling {@link @firebase/firestore/pipelines#Expression.(as:1)} on {@link @firebase/firestore/pipelines#AggregateFunction} instances. Each aggregation\n   *       calculates a value (e.g., sum, average, count) based on the documents within its group.</li>\n   * </ul>\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Calculate the average rating for each genre.\n   * firestore.pipeline().collection(\"books\")\n   *   .aggregate({\n   *       accumulators: [average(field(\"rating\")).as(\"avg_rating\")],\n   *       groups: [\"genre\"]\n   *       });\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage\n   * list.\n   */\n  aggregate(options: AggregateStageOptions): Pipeline;\n  aggregate(\n    targetOrOptions: AliasedAggregate | AggregateStageOptions,\n    ...rest: AliasedAggregate[]\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options = isAliasedAggregate(targetOrOptions) ? {} : targetOrOptions;\n    const accumulators: AliasedAggregate[] = isAliasedAggregate(targetOrOptions)\n      ? [targetOrOptions, ...rest]\n      : targetOrOptions.accumulators;\n    const groups: Array<Selectable | string> = isAliasedAggregate(\n      targetOrOptions\n    )\n      ? []\n      : targetOrOptions.groups ?? [];\n\n    // Convert user land convenience types to internal types\n    const convertedAccumulators: Map<string, AggregateFunction> =\n      aliasedAggregateToMap(accumulators);\n    const convertedGroups: Map<string, Expression> = selectablesToMap(groups);\n\n    // Create stage object\n    const stage = new Aggregate(\n      convertedGroups,\n      convertedAccumulators,\n      options\n    );\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Performs a vector proximity search on the documents from the previous stage, returning the\n   * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The\n   * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`.\n   *\n   * <p>Example:\n   *\n   * ```typescript\n   * // Find the 10 most similar books based on the book description.\n   * const bookDescription = \"Lorem ipsum...\";\n   * const queryVector: number[] = ...; // compute embedding of `bookDescription`\n   *\n   * firestore.pipeline().collection(\"books\")\n   *     .findNearest({\n   *       field: 'embedding',\n   *       vectorValue: queryVector,\n   *       distanceMeasure: 'euclidean',\n   *       limit: 10,                        // optional\n   *       distanceField: 'computedDistance' // optional\n   *     });\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  findNearest(options: FindNearestStageOptions): Pipeline {\n    // Convert user land convenience types to internal types\n    const field = toField(options.field);\n    const vectorValue = vectorToExpr(options.vectorValue);\n    const distanceField = options.distanceField\n      ? toField(options.distanceField)\n      : undefined;\n    const internalOptions = {\n      distanceField,\n      limit: options.limit,\n      rawOptions: options.rawOptions\n    };\n\n    // Create stage object\n    const stage = new FindNearest(\n      vectorValue,\n      field,\n      options.distanceMeasure,\n      internalOptions\n    );\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  // TODO(search) link to external documentation citing list of supported\n  // expressions, when that documentation is created. List is not maintained\n  // in the SDK because the list will change as the backend enables support.\n  /**\n   * @beta\n   * Add a search stage to the Pipeline. The search stage supports\n   * full-text search and geo search expressions.\n   *\n   * @remarks This must be the first stage of the pipeline.\n   * @remarks A limited set of expressions are supported in the search stage.\n   *\n   * @example\n   * ```typescript\n   * // Full-text search example\n   * firestore.pipeline().collection(\"restaurants\")\n   * .search({\n   *   query: documentMatches(\"waffles OR pancakes\"),\n   *   sort: [\n   *     score().descending(),\n   *   ],\n   *   addFields: [\n   *     score().as(\"searchScore\"),\n   *   ]\n   * })\n   * ```\n   *\n   * @example\n   * ```typescript\n   * // Geo distance search example\n   * const queryLocation = new GeoPoint(0, 0);\n   * db.pipeline().collection('restaurants').search({\n   *   query: field('location').geoDistance(queryLocation).lessThanOrEqual(1000),\n   *   sort: [\n   *     score().descending(),\n   *   ],\n   * })\n   * ```\n   *\n   * @param options - An object that specifies parameters for the stage.\n   * @return A new `Pipeline` object with this stage appended to the stage list.\n   */\n  search(options: SearchStageOptions): Pipeline {\n    // Convert user land convenience types to internal types\n    const addFields: Record<string, Expression> | undefined = options.addFields\n      ? selectablesToObject(options.addFields)\n      : undefined;\n    const query: BooleanExpression = isExpr(options.query)\n      ? options.query\n      : documentMatches(options.query);\n    const sort: Ordering[] | undefined = isOrdering(options.sort)\n      ? [options.sort]\n      : options.sort;\n\n    const select: Record<string, Expression> | undefined = undefined;\n    // TODO(search) enable with backend support\n    // select = options.select\n    //   ? selectablesToObject(options.select)\n    //   : undefined;\n\n    const internalOptions = {\n      ...options,\n      addFields,\n      select,\n      query,\n      sort\n    };\n\n    // Create stage object\n    const stage = new Search(internalOptions);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Sorts the documents from previous stages based on one or more {@link @firebase/firestore/pipelines#Ordering} criteria.\n   *\n   * <p>This stage allows you to order the results of your pipeline. You can specify multiple {@link\n   * @firebase/firestore/pipelines#Ordering} instances to sort by multiple fields in ascending or descending order. If documents\n   * have the same value for a field used for sorting, the next specified ordering will be used. If\n   * all orderings result in equal comparison, the documents are considered equal and the order is\n   * unspecified.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Sort books by rating in descending order, and then by title in ascending order for books\n   * // with the same rating\n   * firestore.pipeline().collection(\"books\")\n   *     .sort(\n   *         field(\"rating\").descending(),\n   *         field(\"title\").ascending()\n   *     );\n   * ```\n   *\n   * @param ordering - The first {@link @firebase/firestore/pipelines#Ordering} instance specifying the sorting criteria.\n   * @param additionalOrderings - Optional additional {@link @firebase/firestore/pipelines#Ordering} instances specifying the additional sorting criteria.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline;\n  /**\n   * Sorts the documents from previous stages based on one or more {@link @firebase/firestore/pipelines#Ordering} criteria.\n   *\n   * <p>This stage allows you to order the results of your pipeline. You can specify multiple {@link\n   * @firebase/firestore/pipelines#Ordering} instances to sort by multiple fields in ascending or descending order. If documents\n   * have the same value for a field used for sorting, the next specified ordering will be used. If\n   * all orderings result in equal comparison, the documents are considered equal and the order is\n   * unspecified.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Sort books by rating in descending order, and then by title in ascending order for books\n   * // with the same rating\n   * firestore.pipeline().collection(\"books\")\n   *     .sort(\n   *         field(\"rating\").descending(),\n   *         field(\"title\").ascending()\n   *     );\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  sort(options: SortStageOptions): Pipeline;\n  sort(\n    orderingOrOptions: Ordering | SortStageOptions,\n    ...additionalOrderings: Ordering[]\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options = isOrdering(orderingOrOptions) ? {} : orderingOrOptions;\n    const orderings: Ordering[] = isOrdering(orderingOrOptions)\n      ? [orderingOrOptions, ...additionalOrderings]\n      : orderingOrOptions.orderings;\n\n    // Create stage object\n    const stage = new Sort(orderings, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Fully overwrites all fields in a document with those coming from a nested map.\n   *\n   * <p>This stage allows you to emit a map value as a document. Each key of the map becomes a field\n   * on the document that contains the corresponding value.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Input.\n   * // {\n   * //  'name': 'John Doe Jr.',\n   * //  'parents': {\n   * //    'father': 'John Doe Sr.',\n   * //    'mother': 'Jane Doe'\n   * //   }\n   * // }\n   *\n   * // Emit parents as document.\n   * firestore.pipeline().collection('people').replaceWith('parents');\n   *\n   * // Output\n   * // {\n   * //  'father': 'John Doe Sr.',\n   * //  'mother': 'Jane Doe'\n   * // }\n   * ```\n   *\n   * @param fieldName - The {@link @firebase/firestore/pipelines#Field} field containing the nested map.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  replaceWith(fieldName: string): Pipeline;\n  /**\n   * Fully overwrites all fields in a document with those coming from a map.\n   *\n   * <p>This stage allows you to emit a map value as a document. Each key of the map becomes a field\n   * on the document that contains the corresponding value.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Input.\n   * // {\n   * //  'name': 'John Doe Jr.',\n   * //  'parents': {\n   * //    'father': 'John Doe Sr.',\n   * //    'mother': 'Jane Doe'\n   * //   }\n   * // }\n   *\n   * // Emit parents as document.\n   * firestore.pipeline().collection('people').replaceWith(map({\n   *   foo: 'bar',\n   *   info: {\n   *     name: field('name')\n   *   }\n   * }));\n   *\n   * // Output\n   * // {\n   * //  'father': 'John Doe Sr.',\n   * //  'mother': 'Jane Doe'\n   * // }\n   * ```\n   *\n   * @param expr - An {@link @firebase/firestore/pipelines#Expression} that when returned evaluates to a map.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  replaceWith(expr: Expression): Pipeline;\n  /**\n   * Fully overwrites all fields in a document with those coming from a map.\n   *\n   * <p>This stage allows you to emit a map value as a document. Each key of the map becomes a field\n   * on the document that contains the corresponding value.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Input.\n   * // {\n   * //  'name': 'John Doe Jr.',\n   * //  'parents': {\n   * //    'father': 'John Doe Sr.',\n   * //    'mother': 'Jane Doe'\n   * //   }\n   * // }\n   *\n   * // Emit parents as document.\n   * firestore.pipeline().collection('people').replaceWith(map({\n   *   foo: 'bar',\n   *   info: {\n   *     name: field('name')\n   *   }\n   * }));\n   *\n   * // Output\n   * // {\n   * //  'father': 'John Doe Sr.',\n   * //  'mother': 'Jane Doe'\n   * // }\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  replaceWith(options: ReplaceWithStageOptions): Pipeline;\n  replaceWith(\n    valueOrOptions: Expression | string | ReplaceWithStageOptions\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    const options =\n      isString(valueOrOptions) || isExpr(valueOrOptions) ? {} : valueOrOptions;\n    const fieldNameOrExpr: string | Expression =\n      isString(valueOrOptions) || isExpr(valueOrOptions)\n        ? valueOrOptions\n        : valueOrOptions.map;\n\n    // Convert user land convenience types to internal types\n    const mapExpr = fieldOrExpression(fieldNameOrExpr);\n\n    // Create stage object\n    const stage = new Replace(mapExpr, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Performs a pseudo-random sampling of the documents from the previous stage.\n   *\n   * <p>This stage will filter documents pseudo-randomly. The parameter specifies how number of\n   * documents to be returned.\n   *\n   * <p>Examples:\n   *\n   * @example\n   * ```typescript\n   * // Sample 25 books, if available.\n   * firestore.pipeline().collection('books')\n   *     .sample(25);\n   * ```\n   *\n   * @param documents - The number of documents to sample.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  sample(documents: number): Pipeline;\n\n  /**\n   * Performs a pseudo-random sampling of the documents from the previous stage.\n   *\n   * <p>This stage will filter documents pseudo-randomly. The 'options' parameter specifies how\n   * sampling will be performed. See {@link @firebase/firestore/pipelines#SampleStageOptions} for more information.\n   *\n   * @example\n   * ```typescript\n   * // Sample 10 books, if available.\n   * firestore.pipeline().collection(\"books\")\n   *     .sample({ documents: 10 });\n   *\n   * // Sample 50% of books.\n   * firestore.pipeline().collection(\"books\")\n   *     .sample({ percentage: 0.5 });\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  sample(options: SampleStageOptions): Pipeline;\n  sample(documentsOrOptions: number | SampleStageOptions): Pipeline {\n    // Process argument union(s) from method overloads\n    const options = isNumber(documentsOrOptions) ? {} : documentsOrOptions;\n    let rate: number;\n    let mode: 'documents' | 'percent';\n    if (isNumber(documentsOrOptions)) {\n      rate = documentsOrOptions;\n      mode = 'documents';\n    } else if (isNumber(documentsOrOptions.documents)) {\n      rate = documentsOrOptions.documents;\n      mode = 'documents';\n    } else {\n      rate = documentsOrOptions.percentage!;\n      mode = 'percent';\n    }\n\n    // Create stage object\n    const stage = new Sample(rate, mode, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Performs union of all documents from two pipelines, including duplicates.\n   *\n   * <p>This stage will pass through documents from previous stage, and also pass through documents\n   * from previous stage of the `other` {@link @firebase/firestore/pipelines#Pipeline} given in parameter. The order of documents\n   * emitted from this stage is undefined.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Emit documents from books collection and magazines collection.\n   * firestore.pipeline().collection('books')\n   *     .union(firestore.pipeline().collection('magazines'));\n   * ```\n   *\n   * @param other - The other {@link @firebase/firestore/pipelines#Pipeline} that is part of union.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  union(other: Pipeline): Pipeline;\n  /**\n   * Performs union of all documents from two pipelines, including duplicates.\n   *\n   * <p>This stage will pass through documents from previous stage, and also pass through documents\n   * from previous stage of the `other` {@link @firebase/firestore/pipelines#Pipeline} given in parameter. The order of documents\n   * emitted from this stage is undefined.\n   *\n   * <p>Example:\n   *\n   * @example\n   * ```typescript\n   * // Emit documents from books collection and magazines collection.\n   * firestore.pipeline().collection('books')\n   *     .union(firestore.pipeline().collection('magazines'));\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  union(options: UnionStageOptions): Pipeline;\n  union(otherOrOptions: Pipeline | UnionStageOptions): Pipeline {\n    // Process argument union(s) from method overloads\n    let options: {};\n    let otherPipeline: Pipeline;\n    if (isPipeline(otherOrOptions)) {\n      options = {};\n      otherPipeline = otherOrOptions;\n    } else {\n      ({ other: otherPipeline, ...options } = otherOrOptions);\n    }\n\n    // Create stage object\n    const stage = new Union(otherPipeline, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Produces a document for each element in an input array.\n   *\n   * For each previous stage document, this stage will emit zero or more augmented documents. The\n   * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will\n   * augment the previous stage document by setting the `alias` field  with the array element value.\n   *\n   * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for\n   * the current input document, returning it as is with the `alias` field absent.\n   *\n   * No documents are emitted when `selectable` evaluates to an empty array.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * // Input:\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tags\": [ \"comedy\", \"space\", \"adventure\" ], ... }\n   *\n   * // Emit a book document for each tag of the book.\n   * firestore.pipeline().collection(\"books\")\n   *     .unnest(field(\"tags\").as('tag'), 'tagIndex');\n   *\n   * // Output:\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tag\": \"comedy\", \"tagIndex\": 0, ... }\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tag\": \"space\", \"tagIndex\": 1, ... }\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tag\": \"adventure\", \"tagIndex\": 2, ... }\n   * ```\n   *\n   * @param selectable - A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents.\n   * @param indexField - An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  unnest(selectable: Selectable, indexField?: string): Pipeline;\n  /**\n   * Produces a document for each element in an input array.\n   *\n   * For each previous stage document, this stage will emit zero or more augmented documents. The\n   * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will\n   * augment the previous stage document by setting the `alias` field  with the array element value.\n   *\n   * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for\n   * the current input document, returning it as is with the `alias` field absent.\n   *\n   * No documents are emitted when `selectable` evaluates to an empty array.\n   *\n   * Example:\n   *\n   * @example\n   * ```typescript\n   * // Input:\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tags\": [ \"comedy\", \"space\", \"adventure\" ], ... }\n   *\n   * // Emit a book document for each tag of the book.\n   * firestore.pipeline().collection(\"books\")\n   *     .unnest(field(\"tags\").as('tag'), 'tagIndex');\n   *\n   * // Output:\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tag\": \"comedy\", \"tagIndex\": 0, ... }\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tag\": \"space\", \"tagIndex\": 1, ... }\n   * // { \"title\": \"The Hitchhiker's Guide to the Galaxy\", \"tag\": \"adventure\", \"tagIndex\": 2, ... }\n   * ```\n   *\n   * @param options - An object that specifies required and optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  unnest(options: UnnestStageOptions): Pipeline;\n  unnest(\n    selectableOrOptions: Selectable | UnnestStageOptions,\n    indexField?: string\n  ): Pipeline {\n    // Process argument union(s) from method overloads\n    let options: { indexField?: Field } & StageOptions;\n    let selectable: Selectable;\n    let indexFieldName: string | undefined;\n    if (isSelectable(selectableOrOptions)) {\n      options = {};\n      selectable = selectableOrOptions;\n      indexFieldName = indexField;\n    } else {\n      ({\n        selectable,\n        indexField: indexFieldName,\n        ...options\n      } = selectableOrOptions);\n    }\n\n    // Convert user land convenience types to internal types\n    const alias = selectable.alias;\n    const expr = selectable.expr as Expression;\n    if (isString(indexFieldName)) {\n      options.indexField = _field(indexFieldName, 'unnest');\n    }\n\n    // Create stage object\n    const stage = new Unnest(alias, expr, options);\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * Adds a raw stage to the pipeline.\n   *\n   * <p>This method provides a flexible way to extend the pipeline's functionality by adding custom\n   * stages. Each raw stage is defined by a unique `name` and a set of `params` that control its\n   * behavior.\n   *\n   * <p>Example (Assuming there is no 'where' stage available in SDK):\n   *\n   * @example\n   * ```typescript\n   * // Assume we don't have a built-in 'where' stage\n   * firestore.pipeline().collection('books')\n   *     .rawStage('where', [field('published').lessThan(1900)]) // Custom 'where' stage\n   *     .select('title', 'author');\n   * ```\n   *\n   * @param name - The unique name of the raw stage to add.\n   * @param params - A list of parameters to configure the raw stage's behavior.\n   * @param options - An object of key value pairs that specifies optional parameters for the stage.\n   * @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.\n   */\n  rawStage(\n    name: string,\n    params: unknown[],\n    options?: { [key: string]: Expression | unknown }\n  ): Pipeline {\n    // Convert user land convenience types to internal types\n    const expressionParams = params.map((value: unknown) => {\n      if (value instanceof Expression) {\n        return value;\n      } else if (value instanceof AggregateFunction) {\n        return value;\n      } else if (isPlainObject(value)) {\n        return _mapValue(value as Record<string, unknown>);\n      } else {\n        return _constant(value, 'rawStage');\n      }\n    });\n\n    // Create stage object\n    const stage = new RawStage(name, expressionParams, options ?? {});\n\n    // Add stage to the pipeline\n    return this._addStage(stage);\n  }\n\n  /**\n   * @internal\n   * @private\n   */\n  _toProto(jsonProtoSerializer: JsonProtoSerializer): ProtoPipeline {\n    const stages: ProtoStage[] = this.stages.map(stage =>\n      stage._toProto(jsonProtoSerializer)\n    );\n    return { stages };\n  }\n\n  private _addStage(stage: Stage): Pipeline {\n    const copy = this.stages.map(s => s);\n    copy.push(stage);\n    return this.newPipeline(this._db, copy);\n  }\n\n  /**\n   * @internal\n   * @private\n   * @param db\n   * @param userDataReader\n   * @param userDataWriter\n   * @param stages\n   * @protected\n   */\n  protected newPipeline(db: Firestore | undefined, stages: Stage[]): Pipeline {\n    return new Pipeline(db, stages);\n  }\n}\n\nexport function isPipeline(val: unknown): val is Pipeline {\n  return val instanceof Pipeline;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport { toPipeline } from '../core/pipeline-util';\nimport { Code, FirestoreError } from '../util/error';\nimport { isString } from '../util/types';\n\nimport { Pipeline } from './pipeline';\nimport {\n  CollectionReference,\n  DocumentReference,\n  isCollectionReference,\n  Query\n} from './reference';\nimport {\n  CollectionGroupSource,\n  CollectionSource,\n  DatabaseSource,\n  DocumentsSource,\n  Stage,\n  SubcollectionSource\n} from './stage';\nimport {\n  CollectionGroupStageOptions,\n  CollectionStageOptions,\n  DatabaseStageOptions,\n  DocumentsStageOptions,\n  SubcollectionStageOptions\n} from './stage_options';\n\n/**\n * Provides the entry point for defining the data source of a Firestore {@link @firebase/firestore/pipelines#Pipeline}.\n *\n * Use the methods of this class (e.g., {@link @firebase/firestore/pipelines#PipelineSource.(collection:1)}, {@link @firebase/firestore/pipelines#PipelineSource.(collectionGroup:1)},\n * {@link @firebase/firestore/pipelines#PipelineSource.(database:1)}, or {@link @firebase/firestore/pipelines#PipelineSource.(documents:1)}) to specify the initial data\n * for your pipeline, such as a collection, a collection group, the entire database, or a set of specific documents.\n */\nexport class PipelineSource<PipelineType> {\n  /**\n   * @internal\n   * @private\n   * @param databaseId\n   * @param _createPipeline\n   */\n  constructor(\n    private databaseId: DatabaseId,\n    /**\n     * @internal\n     * @private\n     */\n    public _createPipeline: (stages: Stage[]) => PipelineType\n  ) {}\n\n  /**\n   * Returns all documents from the entire collection. The collection can be nested.\n   * @param collection - Name or reference to the collection that will be used as the Pipeline source.\n   */\n  collection(collection: string | CollectionReference): PipelineType;\n  /**\n   * Returns all documents from the entire collection. The collection can be nested.\n   * @param options - Options defining how this CollectionStage is evaluated.\n   */\n  collection(options: CollectionStageOptions): PipelineType;\n  collection(\n    collectionOrOptions: string | CollectionReference | CollectionStageOptions\n  ): PipelineType {\n    // Process argument union(s) from method overloads\n    const options =\n      isString(collectionOrOptions) ||\n      isCollectionReference(collectionOrOptions)\n        ? {}\n        : collectionOrOptions;\n    const collectionRefOrString =\n      isString(collectionOrOptions) ||\n      isCollectionReference(collectionOrOptions)\n        ? collectionOrOptions\n        : collectionOrOptions.collection;\n\n    // Validate that a user provided reference is for the same Firestore DB\n    if (isCollectionReference(collectionRefOrString)) {\n      this._validateReference(collectionRefOrString);\n    }\n\n    // Convert user land convenience types to internal types\n    const normalizedCollection = isString(collectionRefOrString)\n      ? (collectionRefOrString as string)\n      : collectionRefOrString.path;\n\n    // Create stage object\n    const stage = new CollectionSource(normalizedCollection, options);\n\n    // Add stage to the pipeline\n    return this._createPipeline([stage]);\n  }\n\n  /**\n   * Returns all documents from a collection ID regardless of the parent.\n   * @param collectionId - ID of the collection group to use as the Pipeline source.\n   */\n  collectionGroup(collectionId: string): PipelineType;\n  /**\n   * Returns all documents from a collection ID regardless of the parent.\n   * @param options - Options defining how this CollectionGroupStage is evaluated.\n   */\n  collectionGroup(options: CollectionGroupStageOptions): PipelineType;\n  collectionGroup(\n    collectionIdOrOptions: string | CollectionGroupStageOptions\n  ): PipelineType {\n    // Process argument union(s) from method overloads\n    let collectionId: string;\n    let options: {};\n    if (isString(collectionIdOrOptions)) {\n      collectionId = collectionIdOrOptions;\n      options = {};\n    } else {\n      ({ collectionId, ...options } = collectionIdOrOptions);\n    }\n\n    // Create stage object\n    const stage = new CollectionGroupSource(collectionId, options);\n\n    // Add stage to the pipeline\n    return this._createPipeline([stage]);\n  }\n\n  /**\n   * Returns all documents from the entire database.\n   */\n  database(): PipelineType;\n  /**\n   * Returns all documents from the entire database.\n   * @param options - Options defining how a DatabaseStage is evaluated.\n   */\n  database(options: DatabaseStageOptions): PipelineType;\n  database(options?: DatabaseStageOptions): PipelineType {\n    // Process argument union(s) from method overloads\n    options = options ?? {};\n\n    // Create stage object\n    const stage = new DatabaseSource(options);\n\n    // Add stage to the pipeline\n    return this._createPipeline([stage]);\n  }\n\n  /**\n   * Set the pipeline's source to the documents specified by the given paths and DocumentReferences.\n   *\n   * @param docs - An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline.\n   * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline.\n   *\n   * @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline.\n   */\n  documents(docs: Array<string | DocumentReference>): PipelineType;\n\n  /**\n   * Set the pipeline's source to the documents specified by the given paths and DocumentReferences.\n   *\n   * @param options - Options defining how this DocumentsStage is evaluated.\n   *\n   * @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline.\n   */\n  documents(options: DocumentsStageOptions): PipelineType;\n  documents(\n    docsOrOptions: Array<string | DocumentReference> | DocumentsStageOptions\n  ): PipelineType {\n    // Process argument union(s) from method overloads\n    let options: {};\n    let docs: Array<string | DocumentReference>;\n    if (Array.isArray(docsOrOptions)) {\n      docs = docsOrOptions;\n      options = {};\n    } else {\n      ({ docs, ...options } = docsOrOptions);\n    }\n\n    // Validate that all user provided references are for the same Firestore DB\n    docs\n      .filter(v => v instanceof DocumentReference)\n      .forEach(dr => this._validateReference(dr as DocumentReference));\n\n    // Convert user land convenience types to internal types\n    const normalizedDocs: string[] = docs.map(doc =>\n      isString(doc) ? doc : doc.path\n    );\n\n    // Create stage object\n    const stage = new DocumentsSource(normalizedDocs, options);\n\n    // Add stage to the pipeline\n    return this._createPipeline([stage]);\n  }\n\n  /**\n   * Convert the given Query into an equivalent Pipeline.\n   *\n   * @param query - A Query to be converted into a Pipeline.\n   *\n   * @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline.\n   */\n  createFrom(query: Query): Pipeline {\n    return toPipeline(query._query, query.firestore);\n  }\n\n  _validateReference(reference: CollectionReference | DocumentReference): void {\n    const refDbId = reference.firestore._databaseId;\n    if (!refDbId.isEqual(this.databaseId)) {\n      throw new FirestoreError(\n        Code.INVALID_ARGUMENT,\n        `Invalid ${\n          reference instanceof CollectionReference\n            ? 'CollectionReference'\n            : 'DocumentReference'\n        }. ` +\n          `The project ID (\"${refDbId.projectId}\") or the database (\"${refDbId.database}\") does not match ` +\n          `the project ID (\"${this.databaseId.projectId}\") and database (\"${this.databaseId.database}\") of the target database of this Pipeline.`\n      );\n    }\n  }\n}\n\n/**\n * @public\n * Creates a new Pipeline targeted at a subcollection relative to the current document context.\n * This creates a pipeline without a database instance, suitable for embedding as a subquery.\n * If executed directly, this pipeline will fail.\n *\n * @param path - The relative path to the subcollection.\n */\nexport function subcollection(path: string): Pipeline;\n/**\n * @public\n * Creates a new Pipeline targeted at a subcollection relative to the current document context.\n * This creates a pipeline without a database instance, suitable for embedding as a subquery.\n * If executed directly, this pipeline will fail.\n *\n * @param options - Options defining how this SubcollectionStage is evaluated.\n */\nexport function subcollection(options: SubcollectionStageOptions): Pipeline;\nexport function subcollection(\n  pathOrOptions: string | SubcollectionStageOptions\n): Pipeline {\n  // Process argument union(s) from method overloads\n  let path: string;\n  let options: {};\n  if (isString(pathOrOptions)) {\n    path = pathOrOptions;\n    options = {};\n  } else {\n    ({ path, ...options } = pathOrOptions);\n  }\n\n  // Create stage object\n  const stage = new SubcollectionSource(path, options);\n\n  return new Pipeline(undefined, [stage]);\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ObjectValue } from '../model/object_value';\nimport { firestoreV1ApiClientInterfaces } from '../protos/firestore_proto_api';\nimport { isOptionalEqual } from '../util/misc';\n\nimport { Field, isField } from './expressions';\nimport { FieldPath } from './field_path';\nimport { Pipeline } from './pipeline';\nimport { DocumentData, DocumentReference, refEqual } from './reference';\nimport { Timestamp } from './timestamp';\nimport { fieldPathFromArgument } from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Represents the results of a Firestore pipeline execution.\n *\n * A `PipelineSnapshot` contains zero or more {@link @firebase/firestore/pipelines#PipelineResult} objects\n * representing the documents returned by a pipeline query. It provides methods\n * to iterate over the documents and access metadata about the query results.\n *\n * @example\n * ```typescript\n * const snapshot: PipelineSnapshot = await firestore\n *   .pipeline()\n *   .collection('myCollection')\n *   .where(field('value').greaterThan(10))\n *   .execute();\n *\n * snapshot.results.forEach(doc => {\n *   console.log(doc.id, '=>', doc.data());\n * });\n * ```\n */\nexport class PipelineSnapshot {\n  private readonly _pipeline: Pipeline;\n  private readonly _executionTime: Timestamp | undefined;\n  private readonly _results: PipelineResult[];\n  constructor(\n    pipeline: Pipeline,\n    results: PipelineResult[],\n    executionTime?: Timestamp\n  ) {\n    this._pipeline = pipeline;\n    this._executionTime = executionTime;\n    this._results = results;\n  }\n\n  /**\n   * An array of all the results in the `PipelineSnapshot`.\n   */\n  get results(): PipelineResult[] {\n    return this._results;\n  }\n\n  /**\n   * The time at which the pipeline producing this result is executed.\n   *\n   * @readonly\n   *\n   */\n  get executionTime(): Timestamp {\n    if (this._executionTime === undefined) {\n      throw new Error(\n        \"'executionTime' is expected to exist, but it is undefined\"\n      );\n    }\n    return this._executionTime;\n  }\n}\n\n/**\n *\n * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the\n * {@link @firebase/firestore/pipelines#PipelineResult.data} or {@link @firebase/firestore/pipelines#PipelineResult.(get:1)} methods.\n *\n * <p>If the PipelineResult represents a non-document result, `ref` will return a undefined\n * value.\n */\nexport class PipelineResult<AppModelType = DocumentData> {\n  private readonly _userDataWriter: AbstractUserDataWriter;\n\n  private readonly _createTime: Timestamp | undefined;\n  private readonly _updateTime: Timestamp | undefined;\n\n  /**\n   * @internal\n   * @private\n   */\n  readonly _ref: DocumentReference | undefined;\n\n  /**\n   * @internal\n   * @private\n   */\n  readonly _fields: ObjectValue;\n\n  /**\n   * @private\n   * @internal\n   *\n   * @param userDataWriter - The serializer used to encode/decode protobuf.\n   * @param ref - The reference to the document.\n   * @param fields - The fields of the Firestore `Document` Protobuf backing\n   * this document.\n   * @param createTime - The time when the document was created if the result is a document, undefined otherwise.\n   * @param updateTime - The time when the document was last updated if the result is a document, undefined otherwise.\n   */\n  constructor(\n    userDataWriter: AbstractUserDataWriter,\n    fields: ObjectValue,\n    ref?: DocumentReference,\n    createTime?: Timestamp,\n    updateTime?: Timestamp\n  ) {\n    this._ref = ref;\n    this._userDataWriter = userDataWriter;\n    this._createTime = createTime;\n    this._updateTime = updateTime;\n    this._fields = fields;\n  }\n\n  /**\n   * The reference of the document, if it is a document; otherwise `undefined`.\n   */\n  get ref(): DocumentReference | undefined {\n    return this._ref;\n  }\n\n  /**\n   * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`.\n   *\n   * @readonly\n   *\n   */\n  get id(): string | undefined {\n    return this._ref?.id;\n  }\n\n  /**\n   * The time the document was created. Undefined if this result is not a document.\n   *\n   * @readonly\n   */\n  get createTime(): Timestamp | undefined {\n    return this._createTime;\n  }\n\n  /**\n   * The time the document was last updated (at the time the snapshot was\n   * generated). Undefined if this result is not a document.\n   *\n   * @readonly\n   */\n  get updateTime(): Timestamp | undefined {\n    return this._updateTime;\n  }\n\n  /**\n   * Retrieves all fields in the result as an object.\n   *\n   * @returns An object containing all fields in the document or\n   * 'undefined' if the document doesn't exist.\n   *\n   * @example\n   * ```\n   * let p = firestore.pipeline().collection('col');\n   *\n   * p.execute().then(results => {\n   *   let data = results[0].data();\n   *   console.log(`Retrieved data: ${JSON.stringify(data)}`);\n   * });\n   * ```\n   */\n  data(): AppModelType {\n    return this._userDataWriter.convertValue(\n      this._fields.value\n    ) as AppModelType;\n  }\n\n  /**\n   * @internal\n   * @private\n   *\n   * Retrieves all fields in the result as a proto value.\n   *\n   * @returns An `Object` containing all fields in the result.\n   */\n  _fieldsProto(): { [key: string]: firestoreV1ApiClientInterfaces.Value } {\n    // Return a cloned value to prevent manipulation of the Snapshot's data\n    return this._fields.clone().value.mapValue.fields!;\n  }\n\n  /**\n   * Retrieves the field specified by `field`.\n   *\n   * @param field - The field path\n   * (e.g. 'foo' or 'foo.bar') to a specific field.\n   * @returns The data at the specified field location or `undefined` if no\n   * such field exists.\n   *\n   * @example\n   * ```\n   * let p = firestore.pipeline().collection('col');\n   *\n   * p.execute().then(results => {\n   *   let field = results[0].get('a.b');\n   *   console.log(`Retrieved field value: ${field}`);\n   * });\n   * ```\n   */\n  // We deliberately use `any` in the external API to not impose type-checking\n  // on end users.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  get(fieldPath: string | FieldPath | Field): any {\n    if (this._fields === undefined) {\n      return undefined;\n    }\n    if (isField(fieldPath)) {\n      fieldPath = fieldPath.fieldName;\n    }\n\n    const value = this._fields.field(\n      fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n    );\n    if (value !== null) {\n      return this._userDataWriter.convertValue(value);\n    }\n  }\n}\n\n/**\n * Test equality of two PipelineResults.\n * @param left - First PipelineResult to compare.\n * @param right - Second PipelineResult to compare.\n */\nexport function pipelineResultEqual(\n  left: PipelineResult,\n  right: PipelineResult\n): boolean {\n  if (left === right) {\n    return true;\n  }\n\n  return (\n    isOptionalEqual(left._ref, right._ref, refEqual) &&\n    isOptionalEqual(left._fields, right._fields, (l, r) => l.isEqual(r))\n  );\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  StructuredPipeline,\n  StructuredPipelineOptions\n} from '../core/structured_pipeline';\nimport { invokeExecutePipeline } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { Pipeline } from './pipeline';\nimport { PipelineResult, PipelineSnapshot } from './pipeline-result';\nimport { PipelineSource } from './pipeline-source';\nimport { DocumentReference } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { Stage } from './stage';\nimport { newUserDataReader, UserDataSource } from './user_data_reader';\n\ndeclare module './database' {\n  interface Firestore {\n    /**\n     * Creates and returns a new PipelineSource, which allows specifying the source stage of a {@link @firebase/firestore/pipelines#Pipeline}.\n     *\n     * @example\n     * ```\n     * let myPipeline: Pipeline = firestore.pipeline().collection('books');\n     * ```\n     */\n    pipeline(): PipelineSource<Pipeline>;\n  }\n}\n\n/**\n * Executes this pipeline and returns a Promise to represent the asynchronous operation.\n *\n * The returned Promise can be used to track the progress of the pipeline execution\n * and retrieve the results (or handle any errors) asynchronously.\n *\n * The pipeline results are returned as a {@link @firebase/firestore/pipelines#PipelineSnapshot} that contains\n * a list of {@link @firebase/firestore/pipelines#PipelineResult} objects. Each {@link @firebase/firestore/pipelines#PipelineResult} typically\n * represents a single key/value map that has passed through all the\n * stages of the pipeline, however this might differ depending on the stages involved in the\n * pipeline. For example:\n *\n * <ul>\n *   <li>If there are no stages or only transformation stages, each {@link @firebase/firestore/pipelines#PipelineResult}\n *       represents a single document.</li>\n *   <li>If there is an aggregation, only a single {@link @firebase/firestore/pipelines#PipelineResult} is returned,\n *       representing the aggregated results over the entire dataset .</li>\n *   <li>If there is an aggregation stage with grouping, each {@link @firebase/firestore/pipelines#PipelineResult} represents a\n *       distinct group and its associated aggregated values.</li>\n * </ul>\n *\n * @example\n * ```typescript\n * const snapshot: PipelineSnapshot = await execute(firestore.pipeline().collection(\"books\")\n *     .where(gt(field(\"rating\"), 4.5))\n *     .select(\"title\", \"author\", \"rating\"));\n *\n * const results: PipelineResults = snapshot.results;\n * ```\n *\n * @param pipeline - The pipeline to execute.\n * @returns A Promise representing the asynchronous pipeline execution.\n */\nexport function execute(pipeline: Pipeline): Promise<PipelineSnapshot> {\n  if (!pipeline._db) {\n    return Promise.reject(\n      new FirestoreError(\n        Code.FAILED_PRECONDITION,\n        'This pipeline was created without a database (e.g., as a subcollection pipeline) and cannot be executed directly. It can only be used as part of another pipeline.'\n      )\n    );\n  }\n  const datastore = getDatastore(pipeline._db);\n  const firestore = cast(pipeline._db, Firestore);\n\n  const userDataReader = newUserDataReader(firestore);\n  const context = userDataReader.createContext(\n    UserDataSource.Argument,\n    'execute'\n  );\n\n  pipeline._readUserData(context);\n  const userDataWriter = new LiteUserDataWriter(firestore);\n\n  const structuredPipelineOptions = new StructuredPipelineOptions({}, {});\n  structuredPipelineOptions._readUserData(context);\n\n  const structuredPipeline: StructuredPipeline = new StructuredPipeline(\n    pipeline,\n    structuredPipelineOptions\n  );\n\n  return invokeExecutePipeline(datastore, structuredPipeline).then(result => {\n    // Get the execution time from the first result.\n    // firestoreClientExecutePipeline returns at least one PipelineStreamElement\n    // even if the returned document set is empty.\n    const executionTime =\n      result.length > 0 ? result[0].executionTime?.toTimestamp() : undefined;\n\n    const docs = result\n      // Currently ignore any response from ExecutePipeline that does\n      // not contain any document data in the `fields` property.\n      .filter(element => !!element.fields)\n      .map(\n        element =>\n          new PipelineResult(\n            userDataWriter,\n            element.fields!,\n            element.key?.path\n              ? new DocumentReference(firestore, null, element.key)\n              : undefined,\n            element.createTime?.toTimestamp(),\n            element.updateTime?.toTimestamp()\n          )\n      );\n\n    return new PipelineSnapshot(pipeline, docs, executionTime);\n  });\n}\n\n/**\n * Creates and returns a new PipelineSource, which allows specifying the source stage of a {@link @firebase/firestore/pipelines#Pipeline}.\n *\n * @example\n * ```\n * let myPipeline: Pipeline = firestore.pipeline().collection('books');\n * ```\n */\nFirestore.prototype.pipeline = function (): PipelineSource<Pipeline> {\n  return new PipelineSource<Pipeline>(this._databaseId, (stages: Stage[]) => {\n    return new Pipeline(this, stages);\n  });\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n  return new FetchConnection(databaseInfo);\n}\n"],"names":["FirebaseError","Error","constructor","code","message","customData","super","this","name","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","replace","PATTERN","_","key","value","String","fullMessage","getModularInstance","_delegate","LogLevel","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","info","INFO","warn","WARN","error","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","method","console","h","m","blockSize","g","Array","C","o","u","n","d","a","c","f","e","charCodeAt","b","t","length","k","F","D","arguments","r","apply","l","v","A","q","p","hasOwnProperty","call","isNaN","isFinite","w","x","z","B","add","G","H","I","J","j","Math","max","floor","ceil","log","LN2","pow","i","toString","abs","E","and","or","xor","digest","reset","update","multiply","modulo","compare","toNumber","getBits","fromNumber","fromString","y","charAt","substring","indexOf","min","parseInt","Integer","global","self","window","User","uid","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","__PRIVATE_logDebug","msg","obj","map","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_formatJSON","JSON","stringify","fail","id","__PRIVATE_messageOrContext","context","__PRIVATE__fail","__PRIVATE_failure","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","__PRIVATE_EmptyAuthCredentialsProvider","getToken","Promise","resolve","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","type","user","Map","headers","__PRIVATE__headers","set","__PRIVATE_authHeaderTokenValue","__PRIVATE_getAuthToken","__PRIVATE_FirstPartyAuthCredentialsProvider","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","apiKey","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","msCrypto","bytes","Uint8Array","getRandomValues","__PRIVATE_i","random","__PRIVATE_AutoId","newId","__PRIVATE_maxMultiple","__PRIVATE_chars","__PRIVATE_autoId","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","undefined","range","len","comparator","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","index","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","startsWith","endsWith","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateDocumentPath","__PRIVATE_isPlainObject","input","getPrototypeOf","__PRIVATE_valueDescription","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_isNegativeZero","__PRIVATE_isNumber","__PRIVATE_isString","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","appCheckToken","streamId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","hostname","__PRIVATE_performRPCRequest","then","response","err","__PRIVATE_logWarn","request","__PRIVATE_expectedResponseCount","__PRIVATE_invokeRPC","__PRIVATE_getGoogApiClientValue","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","__PRIVATE_FetchConnection","S","token","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_objectSize","count","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","atob","DOMException","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","fromCharCode","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","__type__","stringValue","__PRIVATE_getPreviousValue","previousValue","__previous_value__","__PRIVATE_getLocalWriteTime","localWriteTime","__local_write_time__","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","__PRIVATE_arrayEquals","every","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","Filter","FieldFilter","field","op","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","SnapshotVersion","fromTimestamp","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","__PRIVATE_QueryImpl","explicitOrderBy","limitType","startAt","endAt","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","JsonProtoSerializer","__PRIVATE_toBytes","__PRIVATE_fromVersion","version","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_fromPipelineResponse","document","output","transaction","executionTime","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","createTime","updateTime","__PRIVATE_isProtoValueSerializable","_toProto","_protoValueType","__PRIVATE_toMapValue","exp","__PRIVATE_toStringValue","__PRIVATE_toPipelineValue","pipelineValue","__PRIVATE_newSerializer","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","__PRIVATE_invokeStreamingRPC","__PRIVATE_datastoreInstances","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","settings","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","app","_initialized","_terminated","_setSettings","__PRIVATE_makeAuthCredentialsProvider","sessionIndex","iamToken","authTokenFactory","client","_getSettings","_getEmulatorOptions","_freezeSettings","_delete","_terminate","_restart","__PRIVATE_removeComponents","firestore","datastore","delete","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","__PRIVATE_isCollectionReference","pathSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_absolutePath","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","FieldValue","_methodName","GeoPoint","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","__PRIVATE_isWrite","dataSource","__PRIVATE_ParseContextImpl","fieldTransforms","fieldMask","__PRIVATE_validatePath","ne","configuration","__PRIVATE_childPath","__PRIVATE_contextWith","arrayElement","__PRIVATE_validatePathSegment","Y","X","Z","reason","__PRIVATE_createError","methodName","hasConverter","targetDoc","contains","fieldPath","transform","__PRIVATE_UserDataReader","ce","__PRIVATE_parseData","__PRIVATE_looksLikeJsonObject","__PRIVATE_validatePlainObject","description","__PRIVATE_parseObject","__PRIVATE_parsedValue","__PRIVATE_childContextForField","__PRIVATE_parseSentinelFieldValue","__PRIVATE_fieldTransform","_toFieldTransform","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_childContextForArray","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldPathFromDotSeparatedString","search","__PRIVATE_FIELD_PATH_RESERVED","__PRIVATE_hasPath","__PRIVATE_hasDocument","AbstractUserDataWriter","convertValue","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","convertObjectMap","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_LiteUserDataWriter","vector","OptionsUtil","optionDefinitions","_getKnownOptions","knownOptions","__PRIVATE_knownOptionKey","__PRIVATE_optionDefinition","__PRIVATE_optionValue","__PRIVATE_protoValue","nestedOptions","getOptionsProto","serverName","optionsOverride","__PRIVATE_optionsMap","__PRIVATE_mapToArray","__PRIVATE_StructuredPipelineOptions","__PRIVATE__userOptions","__PRIVATE__optionsOverride","__PRIVATE_optionsUtil","indexMode","_readUserData","StructuredPipeline","pipeline","__PRIVATE_isFirestoreValue","__PRIVATE_isITimestamp","__PRIVATE_isILatLng","__PRIVATE_isIArrayValue","__PRIVATE_isIMapValue","fieldReferenceValue","functionValue","__PRIVATE_isIFunction","__PRIVATE_isIPipeline","stages","__PRIVATE_valueToDefaultExpr","Expression","__PRIVATE__map","__PRIVATE__constant","__PRIVATE_vectorToExpr","constant","__PRIVATE_fieldOrExpression","second","FunctionExpression","asBoolean","BooleanExpression","Constant","__PRIVATE_BooleanConstant","Field","__PRIVATE_BooleanField","__PRIVATE_BooleanFunctionExpression","subtract","subtrahend","divide","divisor","mod","equal","notEqual","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","arrayConcat","secondArray","otherArrays","__PRIVATE_exprValues","arrayContains","arrayContainsAll","__PRIVATE_normalizedExpr","__PRIVATE_ListOfExprs","arrayContainsAny","arrayReverse","arrayLength","equalAny","others","__PRIVATE_exprOthers","notEqualAny","exists","charLength","like","__PRIVATE_stringOrExpr","regexContains","regexFind","regexFindAll","regexMatch","stringContains","toLower","toUpper","trim","valueToTrim","ltrim","rtrim","isType","stringConcat","secondString","otherStrings","__PRIVATE_exprs","stringIndexOf","stringRepeat","repetitions","stringReplaceAll","replacement","stringReplaceOne","reverse","arrayFilter","alias","arrayTransform","elementAlias","arrayTransformWithIndex","indexAlias","arraySlice","arrayFirst","arrayFirstN","arrayLast","arrayLastN","arrayMaximum","arrayMaximumN","arrayMinimum","arrayMinimumN","arrayIndexOf","arrayLastIndexOf","arrayIndexOfAll","byteLength","mapGet","subfield","mapSet","moreKeyValues","mapKeys","mapValues","mapEntries","getField","AggregateFunction","_create","sum","average","minimum","maximum","arrayAgg","arrayAggDistinct","countDistinct","logicalMaximum","logicalMinimum","vectorLength","cosineDistance","dotProduct","euclideanDistance","unixMicrosToTimestamp","timestampToUnixMicros","unixMillisToTimestamp","timestampToUnixMillis","unixSecondsToTimestamp","timestampToUnixSeconds","timestampAdd","unit","amount","timestampSubtract","timestampDiff","timestampExtract","part","timezone","documentId","position","__PRIVATE_positionExpr","arrayGet","isError","ifError","catchValue","isAbsent","mapRemove","__PRIVATE_stringExpr","mapMerge","secondMap","otherMaps","__PRIVATE_secondMapExpr","__PRIVATE_otherMapExprs","exponent","trunc","decimalPlaces","ln","sqrt","stringReverse","ifAbsent","__PRIVATE_elseValueOrExpression","ifNull","coalesce","__PRIVATE_delimeterValueOrExpression","log10","arraySum","delimiter","timestampTruncate","granularity","ascending","descending","as","AliasedExpression","params","exprType","__PRIVATE_af","AliasedAggregate","expr","aggregate","selectable","expressionType","fieldName","geoDistance","location","_field","__PRIVATE_documentIdFieldPath","_fromProto","_protoValue","MapValue","__PRIVATE_plainObject","_optionsProto","_options","_optionsUtil","returnValue","_expr","countIf","not","conditional","thenExpr","elseExpr","__PRIVATE_normalizedCatchValue","booleanExpr","tryExpr","mapExpr","firstMap","documentPath","__PRIVATE_fieldExpr","__PRIVATE_lengthExpr","__PRIVATE_normalizedLeft","__PRIVATE_normalizedRight","elements","__PRIVATE__array","__PRIVATE_leftExpr","__PRIVATE_rightExpr","firstArray","__PRIVATE_arrayExpr","__PRIVATE_elementExpr","additionalConditions","condition","__PRIVATE_valueOrField","__PRIVATE_expressionOrFieldName","pattern","__PRIVATE_patternExpr","__PRIVATE_substringExpr","prefix","suffix","__PRIVATE_fieldNameOrExpression","__PRIVATE_fieldOrExpr","subField","countAll","__PRIVATE_expr1","__PRIVATE_expr2","__PRIVATE_normalizedTimestamp","__PRIVATE_normalizedUnit","__PRIVATE_normalizedAmount","currentTimestamp","more","nor","base","rand","elseValue","switchOn","__PRIVATE_delimiterValueOrExpression","__PRIVATE_internalGranularity","variable","__PRIVATE_VariableExpression","variableReferenceValue","currentDocument","__PRIVATE_PipelineValueExpression","jsonProtoSerializer","__PRIVATE_endFieldNameOrExpression","__PRIVATE_startFieldNameOrExpression","__PRIVATE_normalizedEnd","__PRIVATE_normalizedStart","documentMatches","rquery","score","__PRIVATE_toField","Ordering","direction","expression","__PRIVATE_isSelectable","candidate","__PRIVATE_isExpr","__PRIVATE_isOrdering","__PRIVATE_isAliasedAggregate","__PRIVATE_isBooleanExpr","__PRIVATE_isAliasedExpr","__PRIVATE_isField","__PRIVATE_toPipelineBooleanExpr","__PRIVATE_FieldFilterInternal","__PRIVATE_CompositeFilterInternal","__PRIVATE_conditions","__PRIVATE_toPipeline","query","db","__PRIVATE_isCollectionGroupQuery","__PRIVATE_isDocumentQuery","documents","collection","where","__PRIVATE_orders","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","orderBy","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_existsConditions","order","orderings","__PRIVATE_actualOrderings","__PRIVATE_reverseOrderings","__PRIVATE_whereConditionsFromCursor","bound","__PRIVATE_filterFunc","__PRIVATE_cursors","inclusive","__PRIVATE_selectablesToMap","__PRIVATE_selectables","entries","__PRIVATE_selectablesToObject","__PRIVATE_isPipeline","toArrayExpression","Stage","optionsProto","rawOptions","_name","__PRIVATE_AddFields","__PRIVATE_readUserDataHelper","__PRIVATE_RemoveFields","__PRIVATE_Define","__PRIVATE_aliasedExpressions","__PRIVATE_Aggregate","groups","accumulators","__PRIVATE_Distinct","__PRIVATE_CollectionSource","forceIndex","__PRIVATE_formattedCollectionPath","__PRIVATE_CollectionGroupSource","__PRIVATE_SubcollectionSource","__PRIVATE_DatabaseSource","__PRIVATE_DocumentsSource","__PRIVATE_docPaths","__PRIVATE_formattedPaths","__PRIVATE_Where","__PRIVATE_FindNearest","distanceField","vectorValue","distanceMeasure","__PRIVATE_Limit","__PRIVATE_Offset","__PRIVATE_Select","selections","__PRIVATE_Sort","__PRIVATE_Sample","rate","mode","__PRIVATE_Union","__PRIVATE_Unnest","indexField","__PRIVATE_Replace","__PRIVATE_MODE","__PRIVATE_Search","__PRIVATE__searchOptions","retrievalDepth","addFields","select","__PRIVATE_queryEnhancement","languageCode","__PRIVATE_RawStage","__PRIVATE_expressionMap","__PRIVATE_isUserData","__PRIVATE_readableData","Pipeline","_db","__PRIVATE_stage","__PRIVATE_subContext","__PRIVATE_fieldOrOptions","additionalFields","__PRIVATE_normalizedFields","_addStage","removeFields","__PRIVATE_fieldValueOrOptions","__PRIVATE_convertedFields","define","__PRIVATE_aliasedExpressionOrOptions","additionalExpressions","__PRIVATE_convertedExpressions","variables","toScalarExpression","__PRIVATE_selectionOrOptions","additionalSelections","__PRIVATE_normalizedSelections","__PRIVATE_conditionOrOptions","__PRIVATE_offsetOrOptions","__PRIVATE_limitOrOptions","distinct","__PRIVATE_groupOrOptions","additionalGroups","__PRIVATE_convertedGroups","__PRIVATE_targetOrOptions","__PRIVATE_rest","__PRIVATE_convertedAccumulators","__PRIVATE_aliasedAggregateToMap","__PRIVATE_aliasedAggregatees","findNearest","__PRIVATE_internalOptions","__PRIVATE_orderingOrOptions","additionalOrderings","replaceWith","__PRIVATE_valueOrOptions","sample","__PRIVATE_documentsOrOptions","percentage","union","__PRIVATE_otherOrOptions","__PRIVATE_otherPipeline","unnest","__PRIVATE_selectableOrOptions","__PRIVATE_indexFieldName","rawStage","__PRIVATE_expressionParams","__PRIVATE__mapValue","newPipeline","PipelineSource","_createPipeline","__PRIVATE_collectionOrOptions","__PRIVATE_collectionRefOrString","_validateReference","__PRIVATE_normalizedCollection","__PRIVATE_collectionIdOrOptions","__PRIVATE_docsOrOptions","docs","__PRIVATE_dr","__PRIVATE_normalizedDocs","createFrom","reference","__PRIVATE_refDbId","subcollection","__PRIVATE_pathOrOptions","PipelineSnapshot","results","_pipeline","_executionTime","_results","PipelineResult","userDataWriter","ref","_ref","_userDataWriter","_createTime","_updateTime","_fields","_fieldsProto","execute","reject","__PRIVATE_getDatastore","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","__PRIVATE_newDatastore","__PRIVATE_cast","__PRIVATE_newUserDataReader","__PRIVATE_createContext","__PRIVATE_structuredPipelineOptions","async","__PRIVATE_invokeExecutePipeline","structuredPipeline","__PRIVATE_datastoreImpl","__PRIVATE_executePipelineRequest"],"mappings":"sBAyEM,MAAOA,sBAAsBC,MAIjC,WAAAC,CAEWC,EACTC,EAEOC,GAEPC,MAAMF,GALGG,KAAIJ,KAAJA,EAGFI,KAAUF,WAAVA,EAPAE,KAAIC,KAdI,gBA6BfC,OAAOC,eAAeH,KAAMP,cAAcW,WAItCV,MAAMW,mBACRX,MAAMW,kBAAkBL,KAAMM,aAAaF,UAAUG,OAExD,EAGU,MAAAD,aAIX,WAAAX,CACmBa,EACAC,EACAC,GAFAV,KAAOQ,QAAPA,EACAR,KAAWS,YAAXA,EACAT,KAAMU,OAANA,CACf,CAEJ,MAAAH,CACEX,KACGe,GAEH,MAAMb,EAAca,EAAK,IAAoB,CAAA,EACvCC,EAAW,GAAGZ,KAAKQ,WAAWZ,IAC9BiB,EAAWb,KAAKU,OAAOd,GAEvBC,EAAUgB,EAUpB,SAASC,gBAAgBD,EAAkBF,GACzC,OAAOE,EAASE,QAAQC,GAAS,CAACC,EAAGC,KACnC,MAAMC,EAAQR,EAAKO,GACnB,OAAgB,MAATC,EAAgBC,OAAOD,GAAS,IAAID,KAAO,GAEtD,CAf+BJ,CAAgBD,EAAUf,GAAc,QAE7DuB,EAAc,GAAGrB,KAAKS,gBAAgBZ,MAAYe,MAIxD,OAFc,IAAInB,cAAcmB,EAAUS,EAAavB,EAGxD,EAUH,MAAMkB,EAAU,gBClHV,SAAUM,mBACdd,GAEA,OAAIA,GAAYA,EAA+Be,UACrCf,EAA+Be,UAEhCf,CAEX,KCyBYgB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