{"version":3,"file":"pipelines.node.mjs","sources":["../../src/lite-api/pipeline-result.ts","../../src/util/pipeline_util.ts","../../src/lite-api/pipeline.ts","../../src/lite-api/pipeline-source.ts","../../src/api/pipeline.ts","../../src/api/pipeline_impl.ts"],"sourcesContent":["/**\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 { RealtimePipeline } from '../api/realtime_pipeline';\nimport { SnapshotMetadata } from '../api/snapshot';\nimport { ListenOptions } from '../core/event_manager';\nimport { Document } from '../model/document';\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  readonly _metadata: SnapshotMetadata | undefined;\n  readonly _listenOptions: ListenOptions | 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 fields - The fields of the Firestore `Document` Protobuf backing\n   * this document.\n   * @param ref - The reference to the 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   * @param metadata\n   * @param listenOptions\n   */\n  constructor(\n    userDataWriter: AbstractUserDataWriter,\n    fields: ObjectValue,\n    ref?: DocumentReference,\n    createTime?: Timestamp,\n    updateTime?: Timestamp,\n    metadata?: SnapshotMetadata,\n    listenOptions?: ListenOptions\n  ) {\n    this._ref = ref;\n    this._userDataWriter = userDataWriter;\n    this._createTime = createTime;\n    this._updateTime = updateTime;\n    this._fields = fields;\n    this._metadata = metadata;\n    this._listenOptions = listenOptions;\n  }\n\n  /**\n   * @private\n   * @internal\n   * @param userDataWriter\n   * @param doc\n   * @param ref\n   * @param metadata\n   * @param listenOptions\n   */\n  static fromDocument(\n    userDataWriter: AbstractUserDataWriter,\n    doc: Document,\n    ref?: DocumentReference,\n    metadata?: SnapshotMetadata,\n    listenOptions?: ListenOptions\n  ): PipelineResult {\n    return new PipelineResult(\n      userDataWriter,\n      doc.data,\n      ref,\n      doc.createTime.toTimestamp(),\n      doc.version.toTimestamp(),\n      metadata,\n      listenOptions\n    );\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      this._listenOptions?.serverTimestampBehavior\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(\n        value,\n        this._listenOptions?.serverTimestampBehavior\n      );\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\nexport function toPipelineResult(\n  doc: Document,\n  pipeline: RealtimePipeline,\n  listenOptions?: ListenOptions\n): PipelineResult {\n  return PipelineResult.fromDocument(\n    pipeline._userDataWriter,\n    doc,\n    doc.key.path\n      ? new DocumentReference(pipeline._db, null, doc.key)\n      : undefined,\n    undefined,\n    listenOptions\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 {\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 { vector } from '../lite-api/field_value_impl';\nimport type { Pipeline } from '../lite-api/pipeline';\nimport { VectorValue } from '../lite-api/vector_value';\n\nimport { fail } from './assert';\nimport { FirestoreError } from './error';\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 {\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 { UserDataReader, UserData } from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\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 * @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 userDataReader\n   * @param _userDataWriter\n   * @param stages\n   */\n  constructor(\n    /**\n     * @internal\n     * @private\n     */\n    public _db: Firestore | undefined,\n    /**\n     * @internal\n     * @private\n     */\n    readonly userDataReader: UserDataReader | undefined,\n    /**\n     * @internal\n     * @private\n     */\n    public _userDataWriter: AbstractUserDataWriter | undefined,\n    /**\n     * @internal\n     * @private\n     */\n    readonly 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   * <ul>\n   *  <li>{@link @firebase/firestore/pipelines#Field}: References an existing document field.</li>\n   *  <li>{@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)}.</li>\n   * </ul>\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   * <ul>\n   *  <li>{@link @firebase/firestore/pipelines#Field}: References an existing document field.</li>\n   *  <li>{@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)}.</li>\n   * </ul>\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   * ```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   * ```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   * 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   * 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    // Create stage object\n    const stage = new Define(convertedExpressions, options);\n\n    return this._addStage(stage);\n  }\n\n  /**\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   * 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>If 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   * @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   * @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   * @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   * @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   * @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   * @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   * @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   * @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   * <ul>\n   *  <li> `string`: Name of an existing field</li>\n   *  <li> {@link @firebase/firestore/pipelines#Field}: References an existing document field.</li>\n   *  <li> {@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)}.</li>\n   * </ul>\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   * <ul>\n   *  <li>`string`: Name of an existing field</li>\n   *  <li>{@link @firebase/firestore/pipelines#Field}: References an existing document field.</li>\n   *  <li>{@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)}.</li>\n   * </ul>\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   * 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   * @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   * 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   * @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   * @example\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  /**\n   * Add a search stage to the Pipeline. The search stage supports\n   * full-text search and geo search expressions.\n   *\n   * @remarks\n   * This must be the first stage of the pipeline. 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   * @beta\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   * @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   * @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   * @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   * @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   * @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   * @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   * @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   * ```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   * ```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, this.userDataReader, this._userDataWriter, 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 { toPipelineStages } 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';\nimport { UserDataReader, UserDataSource } from './user_data_reader';\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 userDataReader\n   * @param _createPipeline\n   */\n  constructor(\n    private databaseId: DatabaseId,\n    private userDataReader: UserDataReader,\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    // User data must be read in the context of the API method to\n    // provide contextual errors\n    const parseContext = this.userDataReader.createContext(\n      UserDataSource.Argument,\n      'collection'\n    );\n    stage._readUserData(parseContext);\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    // User data must be read in the context of the API method to\n    // provide contextual errors\n    const parseContext = this.userDataReader.createContext(\n      UserDataSource.Argument,\n      'collectionGroup'\n    );\n    stage._readUserData(parseContext);\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    // User data must be read in the context of the API method to\n    // provide contextual errors\n    const parseContext = this.userDataReader.createContext(\n      UserDataSource.Argument,\n      'database'\n    );\n    stage._readUserData(parseContext);\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    // User data must be read in the context of the API method to\n    // provide contextual errors\n    const parseContext = this.userDataReader.createContext(\n      UserDataSource.Argument,\n      'documents'\n    );\n    stage._readUserData(parseContext);\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): PipelineType {\n    return this._createPipeline(\n      toPipelineStages(query._query, query.firestore)\n    );\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, undefined, 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 { Pipeline as LitePipeline } from '../lite-api/pipeline';\nimport { Stage } from '../lite-api/stage';\n\nimport { Firestore } from './database';\n\nexport class Pipeline extends LitePipeline {\n  /**\n   * @internal\n   * @private\n   * @param db\n   * @param userDataReader\n   * @param userDataWriter\n   * @param stages\n   * @param converter\n   * @protected\n   */\n  protected newPipeline(db: Firestore | undefined, stages: Stage[]): Pipeline {\n    return new Pipeline(db, this.userDataReader, this._userDataWriter, stages);\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 { Pipeline } from '../api/pipeline';\nimport { firestoreClientExecutePipeline } from '../core/firestore_client';\nimport {\n  StructuredPipeline,\n  StructuredPipelineOptions\n} from '../core/structured_pipeline';\nimport { Pipeline as LitePipeline } from '../lite-api/pipeline';\nimport { PipelineResult, PipelineSnapshot } from '../lite-api/pipeline-result';\nimport { PipelineSource } from '../lite-api/pipeline-source';\nimport { PipelineExecuteOptions } from '../lite-api/pipeline_options';\nimport { Stage } from '../lite-api/stage';\nimport {\n  newUserDataReader,\n  UserDataSource\n} from '../lite-api/user_data_reader';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { RealtimePipeline } from './realtime_pipeline';\nimport { DocumentReference } from './reference';\nimport { ExpUserDataWriter } from './user_data_writer';\n\ndeclare module './database' {\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  interface Firestore {\n    pipeline(): PipelineSource<Pipeline>;\n    /** @internal */\n    realtimePipeline(): PipelineSource<RealtimePipeline>;\n  }\n}\n\n/**\n * Executes a 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(greaterThan(field(\"rating\"), 4.5))\n *     .select(\"title\", \"author\", \"rating\"));\n *\n * const results: PipelineResult[] = 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: LitePipeline): Promise<PipelineSnapshot>;\n/**\n * Executes a 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(greaterThan(field(\"rating\"), 4.5))\n *     .select(\"title\", \"author\", \"rating\"));\n *\n * const results: PipelineResult[] = snapshot.results;\n * ```\n *\n * @param options - Specifies the pipeline to execute and other options for execute.\n * @returns A Promise representing the asynchronous pipeline execution.\n */\nexport function execute(\n  options: PipelineExecuteOptions\n): Promise<PipelineSnapshot>;\nexport function execute(\n  pipelineOrOptions: LitePipeline | PipelineExecuteOptions\n): Promise<PipelineSnapshot> {\n  const options: PipelineExecuteOptions = !(\n    pipelineOrOptions instanceof LitePipeline\n  )\n    ? pipelineOrOptions\n    : {\n        pipeline: pipelineOrOptions\n      };\n\n  const { pipeline, rawOptions, ...rest } = options;\n\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\n  const firestore = cast(pipeline._db, Firestore);\n  const client = ensureFirestoreConfigured(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 ExpUserDataWriter(firestore);\n\n  const structuredPipelineOptions = new StructuredPipelineOptions(\n    rest,\n    rawOptions\n  );\n  structuredPipelineOptions._readUserData(context);\n\n  const structuredPipeline: StructuredPipeline = new StructuredPipeline(\n    pipeline,\n    structuredPipelineOptions\n  );\n\n  return firestoreClientExecutePipeline(client, structuredPipeline).then(\n    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/**\n * @beta\n * Creates and returns a new PipelineSource, which allows specifying the source stage of a {@link @firebase/firestore/pipelines#Pipeline}.\n *\n * @example\n * ```typescript\n * let myPipeline: Pipeline = firestore.pipeline().collection('books');\n * ```\n */\n// Augment the Firestore class with the pipeline() factory method\nFirestore.prototype.pipeline = function (): PipelineSource<Pipeline> {\n  const userDataReader = newUserDataReader(this);\n  return new PipelineSource<Pipeline>(\n    this._databaseId,\n    userDataReader,\n    (stages: Stage[]) => {\n      return new Pipeline(\n        this,\n        userDataReader,\n        new ExpUserDataWriter(this),\n        stages\n      );\n    }\n  );\n};\n\n/** @internal */\nexport function _enableRealtimePipeline(firestore: Firestore): void {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  (firestore as any).realtimePipeline =\n    function (): PipelineSource<RealtimePipeline> {\n      const userDataReader = newUserDataReader(this);\n      return new PipelineSource<RealtimePipeline>(\n        this._databaseId,\n        userDataReader,\n        (stages: Stage[]) => {\n          return new RealtimePipeline(\n            this,\n            newUserDataReader(this),\n            new ExpUserDataWriter(this),\n            stages\n          );\n        }\n      );\n    };\n}\n"],"names":["isPipeline","Pipeline","LitePipeline"],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAkBH;;;;;;;;;;;;;;;;;;;AAmBG;MACU,gBAAgB,CAAA;AAI3B,IAAA,WAAA,CACE,QAAkB,EAClB,OAAyB,EACzB,aAAyB,EAAA;AAEzB,QAAA,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;AAC1B,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;AACpC,QAAA,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;KACzB;AAED;;AAEG;AACH,IAAA,IAAI,OAAO,GAAA;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;KACtB;AAED;;;;;AAKG;AACH,IAAA,IAAI,aAAa,GAAA;AACf,QAAA,IAAI,IAAI,CAAC,cAAc,KAAK,SAAS,EAAE;AACrC,YAAA,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;SACH;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;KAC5B;AACF,CAAA;AAED;;;;;;;AAOG;MACU,cAAc,CAAA;AAqBzB;;;;;;;;;;;;AAYG;AACH,IAAA,WAAA,CACE,cAAsC,EACtC,MAAmB,EACnB,GAAuB,EACvB,UAAsB,EACtB,UAAsB,EACtB,QAA2B,EAC3B,aAA6B,EAAA;AAE7B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;AAChB,QAAA,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;AACtC,QAAA,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;AAC9B,QAAA,IAAI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