@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
902 lines (883 loc) • 37.3 kB
JavaScript
import { _ as a, a as s, b as e, c as t, d as n, W as i, e as r, f as o, g as c, h as l, i as u, j as h, k as d, F as p, l as m, m as b, n as w, o as f, p as g, q as y, r as x, s as P, t as T, u as v, v as A, w as F, x as S, y as E, z as I, A as R, B as D, C as q, D as M, E as O, G as j, H as C, I as _, J as L, K as $, L as N, M as W, N as G, O as U, P as V, Q as k, U as B, R as Q, S as z, T as H, V as J, X as K, Y as X, Z as Y, $ as Z, a0 as aa, a1 as sa, a2 as ea, a3 as ta, a4 as na, a5 as ia, a6 as ra, a7 as oa, a8 as la, a9 as ua, aa as ha, ab as da, ac as pa, ad as ma, ae as wa, af as fa, ag as ga } from "./common.js";
export { ah as AliasedAggregate, ai as AliasedExpression, aj as AliasedWindowFunction, ak as BooleanExpression, al as Bytes, am as Field, an as FieldPath, ao as FieldValue, ap as GeoPoint, aq as Ordering, ar as Query, as as QueryDocumentSnapshot, at as SnapshotMetadata, au as Timestamp, av as VectorValue, aw as WindowFunction, ax as _internalPipelineToExecutePipelineRequestProto, ay as abs, az as add, aA as and, aB as array, aC as arrayAgg, aD as arrayAggDistinct, aE as arrayConcat, aF as arrayContains, aG as arrayContainsAll, aH as arrayContainsAny, aI as arrayFilter, aJ as arrayFirst, aK as arrayFirstN, aL as arrayGet, aM as arrayIndexOf, aN as arrayIndexOfAll, aO as arrayLast, aP as arrayLastIndexOf, aQ as arrayLastN, aR as arrayLength, aS as arrayMaximum, aT as arrayMaximumN, aU as arrayMinimum, aV as arrayMinimumN, aW as arraySlice, aX as arraySum, aY as arrayTransform, aZ as arrayTransformWithIndex, a_ as ascending, a$ as average, b0 as byteLength, b1 as ceil, b2 as charLength, b3 as coalesce, b4 as collectionId, b5 as concat, b6 as conditional, b7 as constant, b8 as cosineDistance, b9 as count, ba as countAll, bb as countDistinct, bc as countIf, bd as currentDocument, be as currentTimestamp, bf as descending, bg as divide, bh as documentId, bi as dotProduct, bj as endsWith, bk as equal, bl as equalAny, bm as euclideanDistance, bn as exists, bo as exp, bp as first, bq as floor, br as geoDistance, bs as greaterThan, bt as greaterThanOrEqual, bu as ifAbsent, bv as ifError, bw as ifNull, bx as isAbsent, by as isError, bz as isType, bA as join, bB as last, bC as length, bD as lessThan, bE as lessThanOrEqual, bF as like, bG as ln, bH as log, bI as log10, bJ as logicalMaximum, bK as logicalMinimum, bL as ltrim, bM as map, bN as mapEntries, bO as mapGet, bP as mapKeys, bQ as mapMerge, bR as mapRemove, bS as mapSet, bT as mapValues, bU as maximum, bV as minimum, bW as mod, bX as multiply, bY as nor, bZ as not, b_ as notEqual, b$ as notEqualAny, c0 as or, c1 as parent, c2 as pow, c3 as rand, c4 as rank, c5 as regexContains, c6 as regexFind, c7 as regexFindAll, c8 as regexMatch, c9 as reverse, ca as round, cb as rtrim, cc as score, cd as split, ce as sqrt, cf as startsWith, cg as stringConcat, ch as stringContains, ci as stringIndexOf, cj as stringRepeat, ck as stringReplaceAll, cl as stringReplaceOne, cm as stringReverse, cn as substring, co as subtract, cp as sum, cq as switchOn, cr as timestampAdd, cs as timestampDiff, ct as timestampExtract, cu as timestampSubtract, cv as timestampToUnixMicros, cw as timestampToUnixMillis, cx as timestampToUnixSeconds, cy as timestampTruncate, cz as toLower, cA as toUpper, cB as trim, cC as trunc, cD as type, cE as unixMicrosToTimestamp, cF as unixMillisToTimestamp, cG as unixSecondsToTimestamp, cH as variable, cI as vectorLength, cJ as xor } from "./common.js";
import "@firebase/app";
import "@firebase/util";
import "@firebase/webchannel-wrapper/bloom-blob";
import "@firebase/logger";
import "tslib";
import "@firebase/webchannel-wrapper/webchannel-blob";
import "re2js";
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* The Pipeline class provides a flexible and expressive framework for building complex data
* transformation and query pipelines for Firestore.
*
* A pipeline takes data sources, such as Firestore collections or collection groups, and applies
* a series of stages that are chained together. Each stage takes the output from the previous stage
* (or the data source) and produces an output for the next stage (or as the final output of the
* pipeline).
*
* Expressions can be used within each stage to filter and transform data through the stage.
*
* NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline.
* Instead, Firestore only guarantees that the result is the same as if the chained stages were
* executed in order.
*
* @example
* ```typescript
* const db: Firestore; // Assumes a valid firestore instance.
*
* // Example 1: Select specific fields and rename 'rating' to 'bookRating'
* const results1 = await execute(db.pipeline()
* .collection("books")
* .select("title", "author", field("rating").as("bookRating")));
*
* // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950
* const results2 = await execute(db.pipeline()
* .collection("books")
* .where(and(field("genre").equal("Science Fiction"), field("published").greaterThan(1950))));
*
* // Example 3: Calculate the average rating of books published after 1980
* const results3 = await execute(db.pipeline()
* .collection("books")
* .where(field("published").greaterThan(1980))
* .aggregate(average(field("rating")).as("averageRating")));
* ```
*/ let ya = class Pipeline {
/**
* @internal
* @private
* @param _db
* @param userDataReader
* @param _userDataWriter
* @param stages
*/
constructor(
/**
* @internal
* @private
*/
a,
/**
* @internal
* @private
*/
s,
/**
* @internal
* @private
*/
e,
/**
* @internal
* @private
*/
t) {
this._db = a, this.userDataReader = s, this._userDataWriter = e, this.stages = t;
}
_readUserData(a) {
this.stages.forEach((s => {
const e = a.contextWith({
methodName: s._name
});
s._readUserData(e);
}));
}
addFields(t, ...n) {
// Process argument union(s) from method overloads
let i, r;
a(t) ? (i = [ t, ...n ], r = {}) : ({fields: i, ...r} = t);
// Convert user land convenience types to internal types
const o = s(i), c = new e(o, r);
// Create stage object
// Add stage to the pipeline
return this._addStage(c);
}
addWindowFields(a, s, ...e) {
// Process argument union(s) from method overloads
const o = t(a), c = o ? a : {}, l = o ? a.window : a, u = o ? a.fields : [ s, ...e ], h = new n(new i(l), r(u), c);
// The whole options object is forwarded, including `window` and `fields`.
// That is safe because `OptionsUtil` only serializes keys declared in the
// stage's option definitions, and this stage declares none.
// Add stage to the pipeline
return this._addStage(h);
}
removeFields(a, ...s) {
// Process argument union(s) from method overloads
const e = o(a) || c(a) ? {} : a, t = (o(a) || c(a) ? [ a, ...s ] : a.fields).map((a => c(a) ? l(a) : a)), n = new u(t, e);
// Add stage to the pipeline
return this._addStage(n);
}
define(a, ...e) {
// Process argument union(s) from method overloads
const t = h(a) ? {} : a, n = h(a) ? [ a, ...e ] : a.variables, i = s(n), r = new d(i, t);
return this._addStage(r);
}
/**
* Converts this Pipeline into an expression that evaluates to an array of results.
*
* <p>Result Unwrapping:</p>
* <ul>
* <li>If the items have a single field, their values are unwrapped and returned directly in the array.</li>
* <li>If the items have multiple fields, they are returned as objects in the array</li>
* </ul>
*
* @example
* ```typescript
* // Get a list of reviewers for each book
* db.pipeline().collection("books")
* .define(field("id").as("book_id"))
* .addFields(
* db.pipeline().collection("reviews")
* .where(field("book_id").equal(variable("book_id")))
* .select(field("reviewer"))
* .toArrayExpression()
* .as("reviewers")
* )
* ```
*
* Output:
* ```json
* [
* {
* "id": "1",
* "title": "1984",
* "reviewers": ["Alice", "Bob"]
* }
* ]
* ```
*
* Multiple Fields:
* ```typescript
* // Get a list of reviews (reviewer and rating) for each book
* db.pipeline().collection("books")
* .define(field("id").as("book_id"))
* .addFields(
* db.pipeline().collection("reviews")
* .where(field("book_id").equal(variable("book_id")))
* .select(field("reviewer"), field("rating"))
* .toArrayExpression()
* .as("reviews"))
* ```
*
* Output:
* ```json
* [
* {
* "id": "1",
* "title": "1984",
* "reviews": [
* { "reviewer": "Alice", "rating": 5 },
* { "reviewer": "Bob", "rating": 4 }
* ]
* }
* ]
* ```
*
* @returns An `Expression` representing the execution of this pipeline.
*/ toArrayExpression() {
return new p("array", [ m(this) ]);
}
/**
* Converts this Pipeline into an expression that evaluates to a single scalar result.
*
* <p><b>Runtime Validation:</b> The runtime validates that the result set contains zero or one item. If
* zero items, it evaluates to `null`.</p>
*
* <p>Result Unwrapping:</p>
* <ul>
* <li>If the item has a single field, its value is unwrapped and returned directly.</li>
* <li>If the item has multiple fields, they are returned as an object.</li>
* </ul>
*
* @example
* ```typescript
* // Calculate average rating for a restaurant
* db.pipeline().collection("restaurants").addFields(
* db.pipeline().collection("reviews")
* .where(field("restaurant_id").equal(variable("rid")))
* .aggregate(average("rating").as("avg"))
* // Unwraps the single "avg" field to a scalar double
* .toScalarExpression().as("average_rating")
* )
* ```
*
* Output:
* ```json
* {
* "name": "The Burger Joint",
* "average_rating": 4.5
* }
* ```
*
* Multiple Fields:
* ```typescript
* // Calculate average rating AND count for a restaurant
* db.pipeline().collection("restaurants").addFields(
* db.pipeline().collection("reviews")
* .where(field("restaurant_id").equal(variable("rid")))
* .aggregate(
* average("rating").as("avg"),
* count().as("count")
* )
* // Returns an object with "avg" and "count" fields
* .toScalarExpression().as("stats")
* )
* ```
*
* Output:
* ```json
* {
* "name": "The Burger Joint",
* "stats": {
* "avg": 4.5,
* "count": 100
* }
* }
* ```
*
* @returns An `Expression` representing the execution of this pipeline.
*/ toScalarExpression() {
return new p("scalar", [ m(this) ]);
}
select(e, ...t) {
// Process argument union(s) from method overloads
const n = a(e) || c(e) ? {} : e, i = a(e) || c(e) ? [ e, ...t ] : e.selections, r = s(i), o = new b(r, n);
// Add stage to the pipeline
return this._addStage(o);
}
where(a) {
// Process argument union(s) from method overloads
const s = w(a) ? {} : a, e = w(a) ? a : a.condition, t = new f(e, s);
// Add stage to the pipeline
return this._addStage(t);
}
offset(a) {
// Process argument union(s) from method overloads
let s, e;
g(a) ? (s = {}, e = a) : (s = a, e = a.offset);
// Create stage object
const t = new y(e, s);
// Add stage to the pipeline
return this._addStage(t);
}
limit(a) {
// Process argument union(s) from method overloads
const s = g(a) ? {} : a, e = g(a) ? a : a.limit, t = new x(e, s);
// Add stage to the pipeline
return this._addStage(t);
}
distinct(e, ...t) {
// Process argument union(s) from method overloads
const n = c(e) || a(e) ? {} : e, i = c(e) || a(e) ? [ e, ...t ] : e.groups, r = s(i), o = new P(r, n);
// Add stage to the pipeline
return this._addStage(o);
}
aggregate(a, ...e) {
// Process argument union(s) from method overloads
const t = T(a) ? {} : a, n = T(a) ? [ a, ...e ] : a.accumulators, i = T(a) ? [] : a.groups ?? [], o = r(n), c = s(i), l = new v(c, o, t);
// Add stage to the pipeline
return this._addStage(l);
}
/**
* Performs a vector proximity search on the documents from the previous stage, returning the
* K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The
* returned documents will be sorted in order from nearest to furthest from the query `vectorValue`.
*
* @example
* ```typescript
* // Find the 10 most similar books based on the book description.
* const bookDescription = "Lorem ipsum...";
* const queryVector: number[] = ...; // compute embedding of `bookDescription`
*
* firestore.pipeline().collection("books")
* .findNearest({
* field: 'embedding',
* vectorValue: queryVector,
* distanceMeasure: 'euclidean',
* limit: 10, // optional
* distanceField: 'computedDistance' // optional
* });
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.
*/ findNearest(a) {
// Convert user land convenience types to internal types
const s = A(a.field), e = F(a.vectorValue), t = {
distanceField: a.distanceField ? A(a.distanceField) : void 0,
limit: a.limit,
rawOptions: a.rawOptions
}, n = new S(e, s, a.distanceMeasure, t);
// Add stage to the pipeline
return this._addStage(n);
}
// TODO(search) link to external documentation citing list of supported
// expressions, when that documentation is created. List is not maintained
// in the SDK because the list will change as the backend enables support.
/**
* Add a search stage to the Pipeline. The search stage supports
* full-text search and geo search expressions.
*
* @remarks
* This must be the first stage of the pipeline. A limited set of expressions are supported in the search stage.
*
* @example
* ```typescript
* // Full-text search example
* firestore.pipeline().collection("restaurants")
* .search({
* query: documentMatches("waffles OR pancakes"),
* sort: [
* score().descending(),
* ],
* addFields: [
* score().as("searchScore"),
* ]
* })
* ```
*
* @example
* ```typescript
* // Geo distance search example
* const queryLocation = new GeoPoint(0, 0);
* db.pipeline().collection('restaurants').search({
* query: field('location').geoDistance(queryLocation).lessThanOrEqual(1000),
* sort: [
* score().descending(),
* ],
* })
* ```
*
* @param options - An object that specifies parameters for the stage.
* @return A new `Pipeline` object with this stage appended to the stage list.
*/
search(a) {
// Convert user land convenience types to internal types
const s = a.addFields ? E(a.addFields) : void 0, e = I(a.query) ? a.query : R(a.query), t = D(a.sort) ? [ a.sort ] : a.sort, n = {
...a,
addFields: s,
select: undefined,
query: e,
sort: t
}, i = new q(n);
// Add stage to the pipeline
return this._addStage(i);
}
sort(a, ...s) {
// Process argument union(s) from method overloads
const e = D(a) ? {} : a, t = D(a) ? [ a, ...s ] : a.orderings, n = new M(t, e);
// Add stage to the pipeline
return this._addStage(n);
}
replaceWith(a) {
// Process argument union(s) from method overloads
const s = c(a) || I(a) ? {} : a, e = c(a) || I(a) ? a : a.map, t = m(e), n = new O(t, s);
// Add stage to the pipeline
return this._addStage(n);
}
sample(a) {
// Process argument union(s) from method overloads
const s = g(a) ? {} : a;
let e, t;
g(a) ? (e = a, t = "documents") : g(a.documents) ? (e = a.documents, t = "documents") : (e = a.percentage,
t = "percent");
// Create stage object
const n = new j(e, t, s);
// Add stage to the pipeline
return this._addStage(n);
}
union(a) {
// Process argument union(s) from method overloads
let s, e;
!function __PRIVATE_isPipeline(a) {
return a instanceof ya;
}
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Represents the results of a Firestore pipeline execution.
*
* A `PipelineSnapshot` contains zero or more {@link @firebase/firestore/pipelines#PipelineResult} objects
* representing the documents returned by a pipeline query. It provides methods
* to iterate over the documents and access metadata about the query results.
*
* @example
* ```typescript
* const snapshot: PipelineSnapshot = await firestore
* .pipeline()
* .collection('myCollection')
* .where(field('value').greaterThan(10))
* .execute();
*
* snapshot.results.forEach(doc => {
* console.log(doc.id, '=>', doc.data());
* });
* ```
*/ (a) ? ({other: e, ...s} = a) : (s = {}, e = a);
// Create stage object
const t = new C(e, s);
// Add stage to the pipeline
return this._addStage(t);
}
unnest(s, e) {
// Process argument union(s) from method overloads
let t, n, i;
a(s) ? (t = {}, n = s, i = e) : ({selectable: n, indexField: i, ...t} = s);
// Convert user land convenience types to internal types
const r = n.alias, o = n.expr;
c(i) && (t.indexField = _(i, "unnest"));
// Create stage object
const l = new L(r, o, t);
// Add stage to the pipeline
return this._addStage(l);
}
/**
* Adds a raw stage to the pipeline.
*
* <p>This method provides a flexible way to extend the pipeline's functionality by adding custom
* stages. Each raw stage is defined by a unique `name` and a set of `params` that control its
* behavior.
*
* <p>Example (Assuming there is no 'where' stage available in SDK):
*
* @example
* ```typescript
* // Assume we don't have a built-in 'where' stage
* firestore.pipeline().collection('books')
* .rawStage('where', [field('published').lessThan(1900)]) // Custom 'where' stage
* .select('title', 'author');
* ```
*
* @param name - The unique name of the raw stage to add.
* @param params - A list of parameters to configure the raw stage's behavior.
* @param options - An object of key value pairs that specifies optional parameters for the stage.
* @returns A new {@link @firebase/firestore/pipelines#Pipeline} object with this stage appended to the stage list.
*/ rawStage(a, s, e) {
// Convert user land convenience types to internal types
const t = s.map((a => a instanceof $ || a instanceof N ? a : W(a) ? G(a) : U(a, "rawStage"))), n = new V(a, t, e ?? {});
// Create stage object
// Add stage to the pipeline
return this._addStage(n);
}
delete(a = {}) {
return this._addStage(new k(a));
}
update(a, ...e) {
let t, n = {};
h(a) ? t = [ a, ...e ] : a && ({transformedFields: t, ...n} = a);
const i = t && t.length > 0 ? s(t) : void 0;
return this._addStage(new B(i, n));
}
insert(a = {}) {
return this._validateCollectionReference(a.collection), this._addStage(new Q(a));
}
upsert(a, ...s) {
let e = {};
return h(a) ? e = {
additionalFields: [ a, ...s ]
} : a && (e = a), this._validateCollectionReference(e.collection), this._addStage(new z(e));
}
/**
* Validates that a user provided `CollectionReference` targets the same
* Firestore database as this pipeline.
*/ _validateCollectionReference(a) {
if (!this._db || !H(a)) return;
const s = a.firestore._databaseId, e = this._db._databaseId;
if (!s.isEqual(e)) throw new J(K.INVALID_ARGUMENT, `Invalid CollectionReference. The project ID ("${s.projectId}") or the database ("${s.database}") does not match the project ID ("${e.projectId}") and database ("${e.database}") of the target database of this Pipeline.`);
}
/**
* @internal
* @private
*/ _toProto(a) {
return {
stages: this.stages.map((s => s._toProto(a)))
};
}
_addStage(a) {
const s = this.stages.map((a => a));
return s.push(a), this.newPipeline(this._db, s);
}
/**
* @internal
* @private
* @param db
* @param userDataReader
* @param userDataWriter
* @param stages
* @protected
*/ newPipeline(a, s) {
return new Pipeline(a, this.userDataReader, this._userDataWriter, s);
}
};
class PipelineSnapshot {
constructor(a, s, e) {
this._pipeline = a, this._executionTime = e, this._results = s;
}
/**
* An array of all the results in the `PipelineSnapshot`.
*/ get results() {
return this._results;
}
/**
* The time at which the pipeline producing this result is executed.
*
* @readonly
*
*/ get executionTime() {
if (void 0 === this._executionTime) throw new Error("'executionTime' is expected to exist, but it is undefined");
return this._executionTime;
}
}
/**
*
* A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the
* {@link @firebase/firestore/pipelines#PipelineResult.data} or {@link @firebase/firestore/pipelines#PipelineResult.(get:1)} methods.
*
* <p>If the PipelineResult represents a non-document result, `ref` will return a undefined
* value.
*/ class PipelineResult {
/**
* @private
* @internal
*
* @param userDataWriter - The serializer used to encode/decode protobuf.
* @param fields - The fields of the Firestore `Document` Protobuf backing
* this document.
* @param ref - The reference to the document.
* @param createTime - The time when the document was created if the result is a document, undefined otherwise.
* @param updateTime - The time when the document was last updated if the result is a document, undefined otherwise.
* @param metadata
* @param listenOptions
*/
constructor(a, s, e, t, n, i, r) {
this._ref = e, this._userDataWriter = a, this._createTime = t, this._updateTime = n,
this._fields = s, this._metadata = i, this._listenOptions = r;
}
/**
* @private
* @internal
* @param userDataWriter
* @param doc
* @param ref
* @param metadata
* @param listenOptions
*/ static fromDocument(a, s, e, t, n) {
return new PipelineResult(a, s.data, e, s.createTime.toTimestamp(), s.version.toTimestamp(), t, n);
}
/**
* The reference of the document, if it is a document; otherwise `undefined`.
*/ get ref() {
return this._ref;
}
/**
* The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`.
*
* @readonly
*
*/ get id() {
return this._ref?.id;
}
/**
* The time the document was created. Undefined if this result is not a document.
*
* @readonly
*/ get createTime() {
return this._createTime;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated). Undefined if this result is not a document.
*
* @readonly
*/ get updateTime() {
return this._updateTime;
}
/**
* Retrieves all fields in the result as an object.
*
* @returns An object containing all fields in the document or
* 'undefined' if the document doesn't exist.
*
* @example
* ```
* let p = firestore.pipeline().collection('col');
*
* p.execute().then(results => {
* let data = results[0].data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
* ```
*/ data() {
return this._userDataWriter.convertValue(this._fields.value, this._listenOptions?.serverTimestampBehavior);
}
/**
* @internal
* @private
*
* Retrieves all fields in the result as a proto value.
*
* @returns An `Object` containing all fields in the result.
*/ _fieldsProto() {
// Return a cloned value to prevent manipulation of the Snapshot's data
return this._fields.clone().value.mapValue.fields;
}
/**
* Retrieves the field specified by `field`.
*
* @param field - The field path
* (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns The data at the specified field location or `undefined` if no
* such field exists.
*
* @example
* ```
* let p = firestore.pipeline().collection('col');
*
* p.execute().then(results => {
* let field = results[0].get('a.b');
* console.log(`Retrieved field value: ${field}`);
* });
* ```
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get(a) {
if (void 0 === this._fields) return;
o(a) && (a = a.fieldName);
const s = this._fields.field(X("DocumentSnapshot.get", a));
return null !== s ? this._userDataWriter.convertValue(s, this._listenOptions?.serverTimestampBehavior) : void 0;
}
}
/**
* Test equality of two PipelineResults.
* @param left - First PipelineResult to compare.
* @param right - Second PipelineResult to compare.
*/ function pipelineResultEqual(a, s) {
return a === s || Y(a._ref, s._ref, Z) && Y(a._fields, s._fields, ((a, s) => a.isEqual(s)));
}
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provides the entry point for defining the data source of a Firestore {@link @firebase/firestore/pipelines#Pipeline}.
*
* Use the methods of this class (e.g., {@link @firebase/firestore/pipelines#PipelineSource.(collection:1)}, {@link @firebase/firestore/pipelines#PipelineSource.(collectionGroup:1)},
* {@link @firebase/firestore/pipelines#PipelineSource.(database:1)}, or {@link @firebase/firestore/pipelines#PipelineSource.(documents:1)}) to specify the initial data
* for your pipeline, such as a collection, a collection group, the entire database, or a set of specific documents.
*/ class PipelineSource {
/**
* @internal
* @private
* @param databaseId
* @param userDataReader
* @param _createPipeline
*/
constructor(a, s,
/**
* @internal
* @private
*/
e) {
this.databaseId = a, this.userDataReader = s, this._createPipeline = e;
}
collection(a) {
// Process argument union(s) from method overloads
const s = c(a) || H(a) ? {} : a, e = c(a) || H(a) ? a : a.collection;
// Validate that a user provided reference is for the same Firestore DB
H(e) && this._validateReference(e);
// Convert user land convenience types to internal types
const t = c(e) ? e : e.path, n = new aa(t, s), i = this.userDataReader.createContext(3 /* UserDataSource.Argument */ , "collection");
// Create stage object
// Add stage to the pipeline
return n._readUserData(i), this._createPipeline([ n ]);
}
collectionGroup(a) {
// Process argument union(s) from method overloads
let s, e;
c(a) ? (s = a, e = {}) : ({collectionId: s, ...e} = a);
// Create stage object
const t = new sa(s, e), n = this.userDataReader.createContext(3 /* UserDataSource.Argument */ , "collectionGroup");
// User data must be read in the context of the API method to
// provide contextual errors
// Add stage to the pipeline
return t._readUserData(n), this._createPipeline([ t ]);
}
database(a) {
// Create stage object
const s = new ea(
// Process argument union(s) from method overloads
a = a ?? {}), e = this.userDataReader.createContext(3 /* UserDataSource.Argument */ , "database");
// User data must be read in the context of the API method to
// provide contextual errors
// Add stage to the pipeline
return s._readUserData(e), this._createPipeline([ s ]);
}
documents(a) {
// Process argument union(s) from method overloads
let s, e;
Array.isArray(a) ? (e = a, s = {}) : ({docs: e, ...s} = a),
// Validate that all user provided references are for the same Firestore DB
e.filter((a => a instanceof ta)).forEach((a => this._validateReference(a)));
// Convert user land convenience types to internal types
const t = e.map((a => c(a) ? a : a.path)), n = new na(t, s), i = this.userDataReader.createContext(3 /* UserDataSource.Argument */ , "documents");
// Create stage object
// Add stage to the pipeline
return n._readUserData(i), this._createPipeline([ n ]);
}
literals(a) {
let s, e = {};
if (Array.isArray(a)) s = a; else {
if (!W(a) || !Array.isArray(a.documents)) throw new J(K.INVALID_ARGUMENT, "Function literals() requires an array of document objects or a LiteralsStageOptions object with a documents array.");
({documents: s, ...e} = a);
}
const t = new ia(s, e), n = this.userDataReader.createContext(3 /* UserDataSource.Argument */ , "literals");
return t._readUserData(n), this._createPipeline([ t ]);
}
/**
* Convert the given Query into an equivalent Pipeline.
*
* @param query - A Query to be converted into a Pipeline.
*
* @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline.
*/ createFrom(a) {
return this._createPipeline(ra(a._query, a.firestore));
}
_validateReference(a) {
const s = a.firestore._databaseId;
if (!s.isEqual(this.databaseId)) throw new J(K.INVALID_ARGUMENT, `Invalid ${a instanceof oa ? "CollectionReference" : "DocumentReference"}. The project ID ("${s.projectId}") or the database ("${s.database}") does not match the project ID ("${this.databaseId.projectId}") and database ("${this.databaseId.database}") of the target database of this Pipeline.`);
}
}
function subcollection(a) {
// Process argument union(s) from method overloads
let s, e;
c(a) ? (s = a, e = {}) : ({path: s, ...e} = a);
// Create stage object
const t = new la(s, e);
return new ya(void 0, void 0, void 0, [ t ]);
}
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ class Pipeline extends ya {
/**
* @internal
* @private
* @param db
* @param userDataReader
* @param userDataWriter
* @param stages
* @param converter
* @protected
*/
newPipeline(a, s) {
return new Pipeline(a, this.userDataReader, this._userDataWriter, s);
}
}
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ function execute(a) {
const s = a instanceof ya ? {
pipeline: a
} : a, {pipeline: e, rawOptions: t, atomic: n, ...i} = s;
if (!e._db) return Promise.reject(new J(K.FAILED_PRECONDITION, "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."));
const r = ua(e._db, fa), o = ha(r), c = da(r).createContext(3 /* UserDataSource.Argument */ , "execute");
e._readUserData(c);
const l = new pa(r), u = new ma(i, t);
u._readUserData(c);
const h = new ga(e, u);
return wa(o, h, {
atomic: n
}).then((a => {
// Get the execution time from the first result.
// firestoreClientExecutePipeline returns at least one PipelineStreamElement
// even if the returned document set is empty.
const s = a.length > 0 ? a[0].executionTime?.toTimestamp() : void 0, t = a.filter((a => !!a.fields)).map((a => new PipelineResult(l, a.fields, a.key?.path ? new ta(r, null, a.key) : void 0, a.createTime?.toTimestamp(), a.updateTime?.toTimestamp())));
return new PipelineSnapshot(e, t, s);
}));
}
/**
* @beta
* Creates and returns a new PipelineSource, which allows specifying the source stage of a {@link @firebase/firestore/pipelines#Pipeline}.
*
* @example
* ```typescript
* let myPipeline: Pipeline = firestore.pipeline().collection('books');
* ```
*/
// Augment the Firestore class with the pipeline() factory method
fa.prototype.pipeline = function() {
const a = da(this);
return new PipelineSource(this._databaseId, a, (s => new Pipeline(this, a, new pa(this), s)));
};
export { N as AggregateFunction, ta as DocumentReference, $ as Expression, fa as Firestore, p as FunctionExpression, Pipeline, PipelineResult, PipelineSnapshot, PipelineSource, R as documentMatches, execute, l as field, pipelineResultEqual, subcollection };
//# sourceMappingURL=pipelines.js.map