@firebase/firestore 3.5.0 → 3.6.0-canary.0a112bd2a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/firestore/lite/index.d.ts +2 -0
  3. package/dist/firestore/src/api/aggregate.d.ts +43 -0
  4. package/dist/firestore/src/api/database.d.ts +15 -15
  5. package/dist/firestore/src/api.d.ts +2 -0
  6. package/dist/firestore/src/core/count_query_runner.d.ts +32 -0
  7. package/dist/firestore/src/core/firestore_client.d.ts +5 -0
  8. package/dist/firestore/src/core/view.d.ts +1 -0
  9. package/dist/firestore/src/core/view_snapshot.d.ts +3 -2
  10. package/dist/firestore/src/lite-api/aggregate.d.ts +48 -0
  11. package/dist/firestore/src/lite-api/aggregate_types.d.ts +69 -0
  12. package/dist/firestore/src/lite-api/database.d.ts +7 -7
  13. package/dist/firestore/src/platform/node/grpc_connection.d.ts +1 -0
  14. package/dist/firestore/src/protos/firestore_proto_api.d.ts +28 -0
  15. package/dist/firestore/src/remote/connection.d.ts +7 -0
  16. package/dist/firestore/src/remote/datastore.d.ts +2 -0
  17. package/dist/firestore/src/remote/remote_event.d.ts +2 -2
  18. package/dist/firestore/src/remote/rest_connection.d.ts +1 -0
  19. package/dist/firestore/src/remote/serializer.d.ts +2 -1
  20. package/dist/firestore/test/integration/api/aggregation.test.d.ts +17 -0
  21. package/dist/firestore/test/integration/api_internal/aggregation.test.d.ts +17 -0
  22. package/dist/firestore/test/integration/util/helpers.d.ts +1 -0
  23. package/dist/firestore/test/unit/specs/spec_test_components.d.ts +1 -0
  24. package/dist/firestore/test/util/api_helpers.d.ts +1 -1
  25. package/dist/index.d.ts +196 -14
  26. package/dist/index.esm2017.js +4633 -4428
  27. package/dist/index.esm2017.js.map +1 -1
  28. package/dist/index.esm5.js +4706 -4498
  29. package/dist/index.esm5.js.map +1 -1
  30. package/dist/index.node.cjs.js +1021 -632
  31. package/dist/index.node.cjs.js.map +1 -1
  32. package/dist/index.node.mjs +1019 -634
  33. package/dist/index.node.mjs.map +1 -1
  34. package/dist/index.rn.js +4637 -4432
  35. package/dist/index.rn.js.map +1 -1
  36. package/dist/internal.d.ts +144 -21
  37. package/dist/lite/firestore/lite/index.d.ts +2 -0
  38. package/dist/lite/firestore/src/api/aggregate.d.ts +43 -0
  39. package/dist/lite/firestore/src/api/database.d.ts +15 -15
  40. package/dist/lite/firestore/src/api.d.ts +2 -0
  41. package/dist/lite/firestore/src/core/count_query_runner.d.ts +32 -0
  42. package/dist/lite/firestore/src/core/firestore_client.d.ts +5 -0
  43. package/dist/lite/firestore/src/core/view.d.ts +1 -0
  44. package/dist/lite/firestore/src/core/view_snapshot.d.ts +3 -2
  45. package/dist/lite/firestore/src/lite-api/aggregate.d.ts +48 -0
  46. package/dist/lite/firestore/src/lite-api/aggregate_types.d.ts +69 -0
  47. package/dist/lite/firestore/src/lite-api/database.d.ts +7 -7
  48. package/dist/lite/firestore/src/platform/node/grpc_connection.d.ts +1 -0
  49. package/dist/lite/firestore/src/protos/firestore_proto_api.d.ts +28 -0
  50. package/dist/lite/firestore/src/remote/connection.d.ts +7 -0
  51. package/dist/lite/firestore/src/remote/datastore.d.ts +2 -0
  52. package/dist/lite/firestore/src/remote/remote_event.d.ts +2 -2
  53. package/dist/lite/firestore/src/remote/rest_connection.d.ts +1 -0
  54. package/dist/lite/firestore/src/remote/serializer.d.ts +2 -1
  55. package/dist/lite/firestore/test/integration/api/aggregation.test.d.ts +17 -0
  56. package/dist/lite/firestore/test/integration/api_internal/aggregation.test.d.ts +17 -0
  57. package/dist/lite/firestore/test/integration/util/helpers.d.ts +1 -0
  58. package/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts +1 -0
  59. package/dist/lite/firestore/test/util/api_helpers.d.ts +1 -1
  60. package/dist/lite/index.browser.esm2017.js +1250 -1086
  61. package/dist/lite/index.browser.esm2017.js.map +1 -1
  62. package/dist/lite/index.browser.esm5.js +1394 -1232
  63. package/dist/lite/index.browser.esm5.js.map +1 -1
  64. package/dist/lite/index.d.ts +84 -4
  65. package/dist/lite/index.node.cjs.js +255 -63
  66. package/dist/lite/index.node.cjs.js.map +1 -1
  67. package/dist/lite/index.node.mjs +253 -65
  68. package/dist/lite/index.node.mjs.map +1 -1
  69. package/dist/lite/index.rn.esm2017.js +1257 -1093
  70. package/dist/lite/index.rn.esm2017.js.map +1 -1
  71. package/dist/lite/internal.d.ts +121 -6
  72. package/dist/lite/packages/firestore/dist/lite/index.browser.esm2017.d.ts +227 -142
  73. package/dist/lite/packages/firestore/lite/index.d.ts +2 -0
  74. package/dist/lite/packages/firestore/src/api/aggregate.d.ts +43 -0
  75. package/dist/lite/packages/firestore/src/api/database.d.ts +15 -15
  76. package/dist/lite/packages/firestore/src/api.d.ts +2 -0
  77. package/dist/lite/packages/firestore/src/core/count_query_runner.d.ts +32 -0
  78. package/dist/lite/packages/firestore/src/core/firestore_client.d.ts +5 -0
  79. package/dist/lite/packages/firestore/src/core/view.d.ts +1 -0
  80. package/dist/lite/packages/firestore/src/core/view_snapshot.d.ts +3 -2
  81. package/dist/lite/packages/firestore/src/lite-api/aggregate.d.ts +48 -0
  82. package/dist/lite/packages/firestore/src/lite-api/aggregate_types.d.ts +69 -0
  83. package/dist/lite/packages/firestore/src/lite-api/database.d.ts +7 -7
  84. package/dist/lite/packages/firestore/src/platform/node/grpc_connection.d.ts +1 -0
  85. package/dist/lite/packages/firestore/src/protos/firestore_proto_api.d.ts +28 -0
  86. package/dist/lite/packages/firestore/src/remote/connection.d.ts +7 -0
  87. package/dist/lite/packages/firestore/src/remote/datastore.d.ts +2 -0
  88. package/dist/lite/packages/firestore/src/remote/remote_event.d.ts +2 -2
  89. package/dist/lite/packages/firestore/src/remote/rest_connection.d.ts +1 -0
  90. package/dist/lite/packages/firestore/src/remote/serializer.d.ts +2 -1
  91. package/dist/lite/packages/firestore/test/integration/api/aggregation.test.d.ts +17 -0
  92. package/dist/lite/packages/firestore/test/integration/api_internal/aggregation.test.d.ts +17 -0
  93. package/dist/lite/packages/firestore/test/integration/util/helpers.d.ts +1 -0
  94. package/dist/lite/packages/firestore/test/unit/specs/spec_test_components.d.ts +1 -0
  95. package/dist/lite/packages/firestore/test/util/api_helpers.d.ts +1 -1
  96. package/dist/lite/private.d.ts +119 -4
  97. package/dist/packages/firestore/dist/index.esm2017.d.ts +336 -254
  98. package/dist/packages/firestore/lite/index.d.ts +2 -0
  99. package/dist/packages/firestore/src/api/aggregate.d.ts +43 -0
  100. package/dist/packages/firestore/src/api/database.d.ts +15 -15
  101. package/dist/packages/firestore/src/api.d.ts +2 -0
  102. package/dist/packages/firestore/src/core/count_query_runner.d.ts +32 -0
  103. package/dist/packages/firestore/src/core/firestore_client.d.ts +5 -0
  104. package/dist/packages/firestore/src/core/view.d.ts +1 -0
  105. package/dist/packages/firestore/src/core/view_snapshot.d.ts +3 -2
  106. package/dist/packages/firestore/src/lite-api/aggregate.d.ts +48 -0
  107. package/dist/packages/firestore/src/lite-api/aggregate_types.d.ts +69 -0
  108. package/dist/packages/firestore/src/lite-api/database.d.ts +7 -7
  109. package/dist/packages/firestore/src/platform/node/grpc_connection.d.ts +1 -0
  110. package/dist/packages/firestore/src/protos/firestore_proto_api.d.ts +28 -0
  111. package/dist/packages/firestore/src/remote/connection.d.ts +7 -0
  112. package/dist/packages/firestore/src/remote/datastore.d.ts +2 -0
  113. package/dist/packages/firestore/src/remote/remote_event.d.ts +2 -2
  114. package/dist/packages/firestore/src/remote/rest_connection.d.ts +1 -0
  115. package/dist/packages/firestore/src/remote/serializer.d.ts +2 -1
  116. package/dist/packages/firestore/test/integration/api/aggregation.test.d.ts +17 -0
  117. package/dist/packages/firestore/test/integration/api_internal/aggregation.test.d.ts +17 -0
  118. package/dist/packages/firestore/test/integration/util/helpers.d.ts +1 -0
  119. package/dist/packages/firestore/test/unit/specs/spec_test_components.d.ts +1 -0
  120. package/dist/packages/firestore/test/util/api_helpers.d.ts +1 -1
  121. package/dist/private.d.ts +239 -23
  122. package/package.json +9 -9
@@ -33,7 +33,7 @@ var grpc__namespace = /*#__PURE__*/_interopNamespace(grpc);
33
33
  var protoLoader__namespace = /*#__PURE__*/_interopNamespace(protoLoader);
34
34
 
35
35
  const name = "@firebase/firestore";
36
- const version$1 = "3.5.0";
36
+ const version$1 = "3.6.0-canary.0a112bd2a";
37
37
 
38
38
  /**
39
39
  * @license
@@ -86,7 +86,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
86
86
  User.FIRST_PARTY = new User('first-party-uid');
87
87
  User.MOCK_USER = new User('mock-user');
88
88
 
89
- const version = "9.10.0";
89
+ const version = "9.11.0-canary.0a112bd2a";
90
90
 
91
91
  /**
92
92
  * @license
@@ -7591,9 +7591,9 @@ class RemoteEvent {
7591
7591
  * CURRENT status change to a View, for queries executed in a different tab.
7592
7592
  */
7593
7593
  // PORTING NOTE: Multi-tab only
7594
- static createSynthesizedRemoteEventForCurrentChange(targetId, current) {
7594
+ static createSynthesizedRemoteEventForCurrentChange(targetId, current, resumeToken) {
7595
7595
  const targetChanges = new Map();
7596
- targetChanges.set(targetId, TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current));
7596
+ targetChanges.set(targetId, TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current, resumeToken));
7597
7597
  return new RemoteEvent(SnapshotVersion.min(), targetChanges, targetIdSet(), mutableDocumentMap(), documentKeySet());
7598
7598
  }
7599
7599
  }
@@ -7646,8 +7646,8 @@ class TargetChange {
7646
7646
  * apply a CURRENT status change to a View (for queries executed in a different
7647
7647
  * tab) or for new queries (to raise snapshots with correct CURRENT status).
7648
7648
  */
7649
- static createSynthesizedTargetChangeForCurrentChange(targetId, current) {
7650
- return new TargetChange(ByteString.EMPTY_BYTE_STRING, current, documentKeySet(), documentKeySet(), documentKeySet());
7649
+ static createSynthesizedTargetChangeForCurrentChange(targetId, current, resumeToken) {
7650
+ return new TargetChange(resumeToken, current, documentKeySet(), documentKeySet(), documentKeySet());
7651
7651
  }
7652
7652
  }
7653
7653
 
@@ -8751,6 +8751,21 @@ function toQueryTarget(serializer, target) {
8751
8751
  }
8752
8752
  return result;
8753
8753
  }
8754
+ function toRunAggregationQueryRequest(serializer, target) {
8755
+ const queryTarget = toQueryTarget(serializer, target);
8756
+ return {
8757
+ structuredAggregationQuery: {
8758
+ aggregations: [
8759
+ {
8760
+ count: {},
8761
+ alias: 'count_alias'
8762
+ }
8763
+ ],
8764
+ structuredQuery: queryTarget.structuredQuery
8765
+ },
8766
+ parent: queryTarget.parent
8767
+ };
8768
+ }
8754
8769
  function convertQueryTargetToQuery(target) {
8755
8770
  let path = fromQueryPath(target.parent);
8756
8771
  const query = target.structuredQuery;
@@ -16137,7 +16152,8 @@ function localStoreGetNewDocumentChanges(localStore, collectionGroup) {
16137
16152
  /** Sets the collection group's maximum read time from the given documents. */
16138
16153
  // PORTING NOTE: Multi-Tab only.
16139
16154
  function setMaxReadTime(localStoreImpl, collectionGroup, changedDocs) {
16140
- let readTime = SnapshotVersion.min();
16155
+ let readTime = localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||
16156
+ SnapshotVersion.min();
16141
16157
  changedDocs.forEach((_, doc) => {
16142
16158
  if (doc.readTime.compareTo(readTime) > 0) {
16143
16159
  readTime = doc.readTime;
@@ -17429,6 +17445,11 @@ class GrpcConnection {
17429
17445
  this.firestore = protos['google']['firestore']['v1'];
17430
17446
  this.databasePath = `projects/${databaseInfo.databaseId.projectId}/databases/${databaseInfo.databaseId.database}`;
17431
17447
  }
17448
+ get shouldResourcePathBeIncludedInRequest() {
17449
+ // Both `invokeRPC()` and `invokeStreamingRPC()` ignore their `path` arguments, and expect
17450
+ // the "path" to be part of the given `request`.
17451
+ return true;
17452
+ }
17432
17453
  ensureActiveStub() {
17433
17454
  if (!this.cachedStub) {
17434
17455
  logDebug(LOG_TAG$9, 'Creating Firestore stub.');
@@ -18475,6 +18496,15 @@ const nested = {
18475
18496
  ruby_package: "Google::Cloud::Firestore::V1"
18476
18497
  },
18477
18498
  nested: {
18499
+ AggregationResult: {
18500
+ fields: {
18501
+ aggregateFields: {
18502
+ keyType: "string",
18503
+ type: "Value",
18504
+ id: 2
18505
+ }
18506
+ }
18507
+ },
18478
18508
  DocumentMask: {
18479
18509
  fields: {
18480
18510
  fieldPaths: {
@@ -18825,6 +18855,29 @@ const nested = {
18825
18855
  }
18826
18856
  ]
18827
18857
  },
18858
+ RunAggregationQuery: {
18859
+ requestType: "RunAggregationQueryRequest",
18860
+ responseType: "RunAggregationQueryResponse",
18861
+ responseStream: true,
18862
+ options: {
18863
+ "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery",
18864
+ "(google.api.http).body": "*",
18865
+ "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery",
18866
+ "(google.api.http).additional_bindings.body": "*"
18867
+ },
18868
+ parsedOptions: [
18869
+ {
18870
+ "(google.api.http)": {
18871
+ post: "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery",
18872
+ body: "*",
18873
+ additional_bindings: {
18874
+ post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery",
18875
+ body: "*"
18876
+ }
18877
+ }
18878
+ }
18879
+ ]
18880
+ },
18828
18881
  PartitionQuery: {
18829
18882
  requestType: "PartitionQueryRequest",
18830
18883
  responseType: "PartitionQueryResponse",
@@ -19316,6 +19369,63 @@ const nested = {
19316
19369
  }
19317
19370
  }
19318
19371
  },
19372
+ RunAggregationQueryRequest: {
19373
+ oneofs: {
19374
+ queryType: {
19375
+ oneof: [
19376
+ "structuredAggregationQuery"
19377
+ ]
19378
+ },
19379
+ consistencySelector: {
19380
+ oneof: [
19381
+ "transaction",
19382
+ "newTransaction",
19383
+ "readTime"
19384
+ ]
19385
+ }
19386
+ },
19387
+ fields: {
19388
+ parent: {
19389
+ type: "string",
19390
+ id: 1,
19391
+ options: {
19392
+ "(google.api.field_behavior)": "REQUIRED"
19393
+ }
19394
+ },
19395
+ structuredAggregationQuery: {
19396
+ type: "StructuredAggregationQuery",
19397
+ id: 2
19398
+ },
19399
+ transaction: {
19400
+ type: "bytes",
19401
+ id: 4
19402
+ },
19403
+ newTransaction: {
19404
+ type: "TransactionOptions",
19405
+ id: 5
19406
+ },
19407
+ readTime: {
19408
+ type: "google.protobuf.Timestamp",
19409
+ id: 6
19410
+ }
19411
+ }
19412
+ },
19413
+ RunAggregationQueryResponse: {
19414
+ fields: {
19415
+ result: {
19416
+ type: "AggregationResult",
19417
+ id: 1
19418
+ },
19419
+ transaction: {
19420
+ type: "bytes",
19421
+ id: 2
19422
+ },
19423
+ readTime: {
19424
+ type: "google.protobuf.Timestamp",
19425
+ id: 3
19426
+ }
19427
+ }
19428
+ },
19319
19429
  PartitionQueryRequest: {
19320
19430
  oneofs: {
19321
19431
  queryType: {
@@ -19852,6 +19962,57 @@ const nested = {
19852
19962
  }
19853
19963
  }
19854
19964
  },
19965
+ StructuredAggregationQuery: {
19966
+ oneofs: {
19967
+ queryType: {
19968
+ oneof: [
19969
+ "structuredQuery"
19970
+ ]
19971
+ }
19972
+ },
19973
+ fields: {
19974
+ structuredQuery: {
19975
+ type: "StructuredQuery",
19976
+ id: 1
19977
+ },
19978
+ aggregations: {
19979
+ rule: "repeated",
19980
+ type: "Aggregation",
19981
+ id: 3
19982
+ }
19983
+ },
19984
+ nested: {
19985
+ Aggregation: {
19986
+ oneofs: {
19987
+ operator: {
19988
+ oneof: [
19989
+ "count"
19990
+ ]
19991
+ }
19992
+ },
19993
+ fields: {
19994
+ count: {
19995
+ type: "Count",
19996
+ id: 1
19997
+ },
19998
+ alias: {
19999
+ type: "string",
20000
+ id: 7
20001
+ }
20002
+ },
20003
+ nested: {
20004
+ Count: {
20005
+ fields: {
20006
+ upTo: {
20007
+ type: "google.protobuf.Int64Value",
20008
+ id: 1
20009
+ }
20010
+ }
20011
+ }
20012
+ }
20013
+ }
20014
+ }
20015
+ },
19855
20016
  Cursor: {
19856
20017
  fields: {
19857
20018
  values: {
@@ -21092,6 +21253,19 @@ async function invokeBatchGetDocumentsRpc(datastore, keys) {
21092
21253
  });
21093
21254
  return result;
21094
21255
  }
21256
+ async function invokeRunAggregationQueryRpc(datastore, query) {
21257
+ const datastoreImpl = debugCast(datastore);
21258
+ const request = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToTarget(query));
21259
+ const parent = request.parent;
21260
+ if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {
21261
+ delete request.parent;
21262
+ }
21263
+ const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', parent, request, /*expectedResponseCount=*/ 1);
21264
+ return (response
21265
+ // Omit RunAggregationQueryResponse that only contain readTimes.
21266
+ .filter(proto => !!proto.result)
21267
+ .map(proto => proto.result.aggregateFields));
21268
+ }
21095
21269
  function newPersistentWriteStream(datastore, queue, listener) {
21096
21270
  const datastoreImpl = debugCast(datastore);
21097
21271
  datastoreImpl.verifyInitialized();
@@ -22188,7 +22362,7 @@ class DocumentChangeSet {
22188
22362
  }
22189
22363
  }
22190
22364
  class ViewSnapshot {
22191
- constructor(query, docs, oldDocs, docChanges, mutatedKeys, fromCache, syncStateChanged, excludesMetadataChanges) {
22365
+ constructor(query, docs, oldDocs, docChanges, mutatedKeys, fromCache, syncStateChanged, excludesMetadataChanges, hasCachedResults) {
22192
22366
  this.query = query;
22193
22367
  this.docs = docs;
22194
22368
  this.oldDocs = oldDocs;
@@ -22197,22 +22371,24 @@ class ViewSnapshot {
22197
22371
  this.fromCache = fromCache;
22198
22372
  this.syncStateChanged = syncStateChanged;
22199
22373
  this.excludesMetadataChanges = excludesMetadataChanges;
22374
+ this.hasCachedResults = hasCachedResults;
22200
22375
  }
22201
22376
  /** Returns a view snapshot as if all documents in the snapshot were added. */
22202
- static fromInitialDocuments(query, documents, mutatedKeys, fromCache) {
22377
+ static fromInitialDocuments(query, documents, mutatedKeys, fromCache, hasCachedResults) {
22203
22378
  const changes = [];
22204
22379
  documents.forEach(doc => {
22205
22380
  changes.push({ type: 0 /* Added */, doc });
22206
22381
  });
22207
22382
  return new ViewSnapshot(query, documents, DocumentSet.emptySet(documents), changes, mutatedKeys, fromCache,
22208
22383
  /* syncStateChanged= */ true,
22209
- /* excludesMetadataChanges= */ false);
22384
+ /* excludesMetadataChanges= */ false, hasCachedResults);
22210
22385
  }
22211
22386
  get hasPendingWrites() {
22212
22387
  return !this.mutatedKeys.isEmpty();
22213
22388
  }
22214
22389
  isEqual(other) {
22215
22390
  if (this.fromCache !== other.fromCache ||
22391
+ this.hasCachedResults !== other.hasCachedResults ||
22216
22392
  this.syncStateChanged !== other.syncStateChanged ||
22217
22393
  !this.mutatedKeys.isEqual(other.mutatedKeys) ||
22218
22394
  !queryEquals(this.query, other.query) ||
@@ -22417,7 +22593,7 @@ class QueryListener {
22417
22593
  }
22418
22594
  }
22419
22595
  snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.mutatedKeys, snap.fromCache, snap.syncStateChanged,
22420
- /* excludesMetadataChanges= */ true);
22596
+ /* excludesMetadataChanges= */ true, snap.hasCachedResults);
22421
22597
  }
22422
22598
  let raisedEvent = false;
22423
22599
  if (!this.raisedInitialEvent) {
@@ -22461,8 +22637,11 @@ class QueryListener {
22461
22637
  if (this.options.waitForSyncWhenOnline && maybeOnline) {
22462
22638
  return false;
22463
22639
  }
22464
- // Raise data from cache if we have any documents or we are offline
22465
- return !snap.docs.isEmpty() || onlineState === "Offline" /* Offline */;
22640
+ // Raise data from cache if we have any documents, have cached results before,
22641
+ // or we are offline.
22642
+ return (!snap.docs.isEmpty() ||
22643
+ snap.hasCachedResults ||
22644
+ onlineState === "Offline" /* Offline */);
22466
22645
  }
22467
22646
  shouldRaiseEvent(snap) {
22468
22647
  // We don't need to handle includeDocumentMetadataChanges here because
@@ -22482,7 +22661,7 @@ class QueryListener {
22482
22661
  return false;
22483
22662
  }
22484
22663
  raiseInitialEvent(snap) {
22485
- snap = ViewSnapshot.fromInitialDocuments(snap.query, snap.docs, snap.mutatedKeys, snap.fromCache);
22664
+ snap = ViewSnapshot.fromInitialDocuments(snap.query, snap.docs, snap.mutatedKeys, snap.fromCache, snap.hasCachedResults);
22486
22665
  this.raisedInitialEvent = true;
22487
22666
  this.queryObserver.next(snap);
22488
22667
  }
@@ -22719,6 +22898,7 @@ class View {
22719
22898
  this.query = query;
22720
22899
  this._syncedDocuments = _syncedDocuments;
22721
22900
  this.syncState = null;
22901
+ this.hasCachedResults = false;
22722
22902
  /**
22723
22903
  * A flag whether the view is current with the backend. A view is considered
22724
22904
  * current after it has seen the current flag from the backend and did not
@@ -22913,7 +23093,9 @@ class View {
22913
23093
  }
22914
23094
  else {
22915
23095
  const snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, docChanges.mutatedKeys, newSyncState === 0 /* Local */, syncStateChanged,
22916
- /* excludesMetadataChanges= */ false);
23096
+ /* excludesMetadataChanges= */ false, targetChange
23097
+ ? targetChange.resumeToken.approximateByteSize() > 0
23098
+ : false);
22917
23099
  return {
22918
23100
  snapshot: snap,
22919
23101
  limboChanges
@@ -23040,7 +23222,7 @@ class View {
23040
23222
  */
23041
23223
  // PORTING NOTE: Multi-tab only.
23042
23224
  computeInitialSnapshot() {
23043
- return ViewSnapshot.fromInitialDocuments(this.query, this.documentSet, this.mutatedKeys, this.syncState === 0 /* Local */);
23225
+ return ViewSnapshot.fromInitialDocuments(this.query, this.documentSet, this.mutatedKeys, this.syncState === 0 /* Local */, this.hasCachedResults);
23044
23226
  }
23045
23227
  }
23046
23228
  function compareChangeType(c1, c2) {
@@ -23220,7 +23402,7 @@ async function syncEngineListen(syncEngine, query) {
23220
23402
  }
23221
23403
  const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(targetData.targetId);
23222
23404
  targetId = targetData.targetId;
23223
- viewSnapshot = await initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, status === 'current');
23405
+ viewSnapshot = await initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, status === 'current', targetData.resumeToken);
23224
23406
  }
23225
23407
  return viewSnapshot;
23226
23408
  }
@@ -23228,7 +23410,7 @@ async function syncEngineListen(syncEngine, query) {
23228
23410
  * Registers a view for a previously unknown query and computes its initial
23229
23411
  * snapshot.
23230
23412
  */
23231
- async function initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, current) {
23413
+ async function initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, current, resumeToken) {
23232
23414
  // PORTING NOTE: On Web only, we inject the code that registers new Limbo
23233
23415
  // targets based on view changes. This allows us to only depend on Limbo
23234
23416
  // changes when user code includes queries.
@@ -23237,7 +23419,7 @@ async function initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId,
23237
23419
  /* usePreviousResults= */ true);
23238
23420
  const view = new View(query, queryResult.remoteKeys);
23239
23421
  const viewDocChanges = view.computeDocChanges(queryResult.documents);
23240
- const synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current && syncEngineImpl.onlineState !== "Offline" /* Offline */);
23422
+ const synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current && syncEngineImpl.onlineState !== "Offline" /* Offline */, resumeToken);
23241
23423
  const viewChange = view.applyChanges(viewDocChanges,
23242
23424
  /* updateLimboDocuments= */ syncEngineImpl.isPrimaryClient, synthesizedTargetChange);
23243
23425
  updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);
@@ -23649,10 +23831,15 @@ async function syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine, changes, re
23649
23831
  queriesProcessed.push(syncEngineImpl
23650
23832
  .applyDocChanges(queryView, changes, remoteEvent)
23651
23833
  .then(viewSnapshot => {
23652
- if (viewSnapshot) {
23834
+ // If there are changes, or we are handling a global snapshot, notify
23835
+ // secondary clients to update query state.
23836
+ if (viewSnapshot || remoteEvent) {
23653
23837
  if (syncEngineImpl.isPrimaryClient) {
23654
- syncEngineImpl.sharedClientState.updateQueryState(queryView.targetId, viewSnapshot.fromCache ? 'not-current' : 'current');
23838
+ syncEngineImpl.sharedClientState.updateQueryState(queryView.targetId, (viewSnapshot === null || viewSnapshot === void 0 ? void 0 : viewSnapshot.fromCache) ? 'not-current' : 'current');
23655
23839
  }
23840
+ }
23841
+ // Update views if there are actual changes.
23842
+ if (!!viewSnapshot) {
23656
23843
  newSnaps.push(viewSnapshot);
23657
23844
  const docChanges = LocalViewChanges.fromSnapshot(queryView.targetId, viewSnapshot);
23658
23845
  docChangesInAllViews.push(docChanges);
@@ -23862,7 +24049,7 @@ async function synchronizeQueryViewsAndRaiseSnapshots(syncEngine, targets, trans
23862
24049
  const target = await localStoreGetCachedTarget(syncEngineImpl.localStore, targetId);
23863
24050
  targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, target);
23864
24051
  await initializeViewAndComputeSnapshot(syncEngineImpl, synthesizeTargetToQuery(target), targetId,
23865
- /*current=*/ false);
24052
+ /*current=*/ false, targetData.resumeToken);
23866
24053
  }
23867
24054
  activeQueries.push(targetData);
23868
24055
  }
@@ -23905,7 +24092,7 @@ async function syncEngineApplyTargetState(syncEngine, targetId, state, error) {
23905
24092
  case 'current':
23906
24093
  case 'not-current': {
23907
24094
  const changes = await localStoreGetNewDocumentChanges(syncEngineImpl.localStore, queryCollectionGroup(query[0]));
23908
- const synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(targetId, state === 'current');
24095
+ const synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(targetId, state === 'current', ByteString.EMPTY_BYTE_STRING);
23909
24096
  await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes, synthesizedRemoteEvent);
23910
24097
  break;
23911
24098
  }
@@ -23935,7 +24122,7 @@ async function syncEngineApplyActiveTargetsChange(syncEngine, added, removed) {
23935
24122
  const target = await localStoreGetCachedTarget(syncEngineImpl.localStore, targetId);
23936
24123
  const targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, target);
23937
24124
  await initializeViewAndComputeSnapshot(syncEngineImpl, synthesizeTargetToQuery(target), targetData.targetId,
23938
- /*current=*/ false);
24125
+ /*current=*/ false, targetData.resumeToken);
23939
24126
  remoteStoreListen(syncEngineImpl.remoteStore, targetData);
23940
24127
  }
23941
24128
  for (const targetId of removed) {
@@ -24698,6 +24885,100 @@ function newBundleReader(reader, serializer) {
24698
24885
  return new BundleReaderImpl(reader, serializer);
24699
24886
  }
24700
24887
 
24888
+ /**
24889
+ * @license
24890
+ * Copyright 2022 Google LLC
24891
+ *
24892
+ * Licensed under the Apache License, Version 2.0 (the "License");
24893
+ * you may not use this file except in compliance with the License.
24894
+ * You may obtain a copy of the License at
24895
+ *
24896
+ * http://www.apache.org/licenses/LICENSE-2.0
24897
+ *
24898
+ * Unless required by applicable law or agreed to in writing, software
24899
+ * distributed under the License is distributed on an "AS IS" BASIS,
24900
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24901
+ * See the License for the specific language governing permissions and
24902
+ * limitations under the License.
24903
+ */
24904
+ /**
24905
+ * Represents an aggregation that can be performed by Firestore.
24906
+ */
24907
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
24908
+ class AggregateField {
24909
+ constructor() {
24910
+ /** A type string to uniquely identify instances of this class. */
24911
+ this.type = 'AggregateField';
24912
+ }
24913
+ }
24914
+ /**
24915
+ * The results of executing an aggregation query.
24916
+ */
24917
+ class AggregateQuerySnapshot {
24918
+ /** @hideconstructor */
24919
+ constructor(query, _data) {
24920
+ this._data = _data;
24921
+ /** A type string to uniquely identify instances of this class. */
24922
+ this.type = 'AggregateQuerySnapshot';
24923
+ this.query = query;
24924
+ }
24925
+ /**
24926
+ * Returns the results of the aggregations performed over the underlying
24927
+ * query.
24928
+ *
24929
+ * The keys of the returned object will be the same as those of the
24930
+ * `AggregateSpec` object specified to the aggregation method, and the values
24931
+ * will be the corresponding aggregation result.
24932
+ *
24933
+ * @returns The results of the aggregations performed over the underlying
24934
+ * query.
24935
+ */
24936
+ data() {
24937
+ return this._data;
24938
+ }
24939
+ }
24940
+
24941
+ /**
24942
+ * @license
24943
+ * Copyright 2022 Google LLC
24944
+ *
24945
+ * Licensed under the Apache License, Version 2.0 (the "License");
24946
+ * you may not use this file except in compliance with the License.
24947
+ * You may obtain a copy of the License at
24948
+ *
24949
+ * http://www.apache.org/licenses/LICENSE-2.0
24950
+ *
24951
+ * Unless required by applicable law or agreed to in writing, software
24952
+ * distributed under the License is distributed on an "AS IS" BASIS,
24953
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24954
+ * See the License for the specific language governing permissions and
24955
+ * limitations under the License.
24956
+ */
24957
+ /**
24958
+ * CountQueryRunner encapsulates the logic needed to run the count aggregation
24959
+ * queries.
24960
+ */
24961
+ class CountQueryRunner {
24962
+ constructor(query, datastore, userDataWriter) {
24963
+ this.query = query;
24964
+ this.datastore = datastore;
24965
+ this.userDataWriter = userDataWriter;
24966
+ }
24967
+ run() {
24968
+ return invokeRunAggregationQueryRpc(this.datastore, this.query._query).then(result => {
24969
+ hardAssert(result[0] !== undefined);
24970
+ const counts = Object.entries(result[0])
24971
+ .filter(([key, value]) => key === 'count_alias')
24972
+ .map(([key, value]) => this.userDataWriter.convertValue(value));
24973
+ const countValue = counts[0];
24974
+ hardAssert(typeof countValue === 'number');
24975
+ return Promise.resolve(new AggregateQuerySnapshot(this.query, {
24976
+ count: countValue
24977
+ }));
24978
+ });
24979
+ }
24980
+ }
24981
+
24701
24982
  /**
24702
24983
  * @license
24703
24984
  * Copyright 2017 Google LLC
@@ -25254,6 +25535,26 @@ function firestoreClientTransaction(client, updateFunction, options) {
25254
25535
  });
25255
25536
  return deferred.promise;
25256
25537
  }
25538
+ function firestoreClientRunCountQuery(client, query, userDataWriter) {
25539
+ const deferred = new Deferred();
25540
+ client.asyncQueue.enqueueAndForget(async () => {
25541
+ try {
25542
+ const remoteStore = await getRemoteStore(client);
25543
+ if (!canUseNetwork(remoteStore)) {
25544
+ deferred.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get count result because the client is offline.'));
25545
+ }
25546
+ else {
25547
+ const datastore = await getDatastore(client);
25548
+ const result = new CountQueryRunner(query, datastore, userDataWriter).run();
25549
+ deferred.resolve(result);
25550
+ }
25551
+ }
25552
+ catch (e) {
25553
+ deferred.reject(e);
25554
+ }
25555
+ });
25556
+ return deferred.promise;
25557
+ }
25257
25558
  async function readDocumentFromCache(localStore, docKey, result) {
25258
25559
  try {
25259
25560
  const document = await localStoreReadDocument(localStore, docKey);
@@ -25509,7 +25810,7 @@ class FirestoreSettingsImpl {
25509
25810
  /**
25510
25811
  * The Cloud Firestore service interface.
25511
25812
  *
25512
- * Do not call this constructor directly. Instead, use {@link getFirestore}.
25813
+ * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
25513
25814
  */
25514
25815
  class Firestore$1 {
25515
25816
  /** @hideconstructor */
@@ -26251,7 +26552,7 @@ const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;
26251
26552
  /**
26252
26553
  * The Cloud Firestore service interface.
26253
26554
  *
26254
- * Do not call this constructor directly. Instead, use {@link getFirestore}.
26555
+ * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
26255
26556
  */
26256
26557
  class Firestore extends Firestore$1 {
26257
26558
  /** @hideconstructor */
@@ -26276,8 +26577,8 @@ class Firestore extends Firestore$1 {
26276
26577
  /**
26277
26578
  * Initializes a new instance of {@link Firestore} with the provided settings.
26278
26579
  * Can only be called before any other function, including
26279
- * {@link getFirestore}. If the custom settings are empty, this function is
26280
- * equivalent to calling {@link getFirestore}.
26580
+ * {@link (getFirestore:1)}. If the custom settings are empty, this function is
26581
+ * equivalent to calling {@link (getFirestore:1)}.
26281
26582
  *
26282
26583
  * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
26283
26584
  * be associated.
@@ -26320,9 +26621,17 @@ function getFirestore(appOrDatabaseId, optionalDatabaseId) {
26320
26621
  const databaseId = typeof appOrDatabaseId === 'string'
26321
26622
  ? appOrDatabaseId
26322
26623
  : optionalDatabaseId || DEFAULT_DATABASE_NAME;
26323
- return app._getProvider(app$1, 'firestore').getImmediate({
26624
+ const db = app._getProvider(app$1, 'firestore').getImmediate({
26324
26625
  identifier: databaseId
26325
26626
  });
26627
+ if (!db._initialized) {
26628
+ const firestoreEmulatorHost = util$1.getDefaultEmulatorHost('firestore');
26629
+ if (firestoreEmulatorHost) {
26630
+ const [host, port] = firestoreEmulatorHost.split(':');
26631
+ connectFirestoreEmulator(db, host, parseInt(port, 10));
26632
+ }
26633
+ }
26634
+ return db;
26326
26635
  }
26327
26636
  /**
26328
26637
  * @internal
@@ -26344,7 +26653,7 @@ function configureFirestore(firestore) {
26344
26653
  * Attempts to enable persistent storage, if possible.
26345
26654
  *
26346
26655
  * Must be called before any other functions (other than
26347
- * {@link initializeFirestore}, {@link getFirestore} or
26656
+ * {@link initializeFirestore}, {@link (getFirestore:1)} or
26348
26657
  * {@link clearIndexedDbPersistence}.
26349
26658
  *
26350
26659
  * If this fails, `enableIndexedDbPersistence()` will reject the promise it
@@ -26468,7 +26777,7 @@ function canFallbackFromIndexedDbError(error) {
26468
26777
  * Must be called while the {@link Firestore} instance is not started (after the app is
26469
26778
  * terminated or when the app is first initialized). On startup, this function
26470
26779
  * must be called before other functions (other than {@link
26471
- * initializeFirestore} or {@link getFirestore})). If the {@link Firestore}
26780
+ * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
26472
26781
  * instance is still running, the promise will be rejected with the error code
26473
26782
  * of `failed-precondition`.
26474
26783
  *
@@ -26552,7 +26861,7 @@ function disableNetwork(firestore) {
26552
26861
  * may be used. Any other function will throw a `FirestoreError`.
26553
26862
  *
26554
26863
  * To restart after termination, create a new instance of FirebaseFirestore with
26555
- * {@link getFirestore}.
26864
+ * {@link (getFirestore:1)}.
26556
26865
  *
26557
26866
  * Termination does not cancel any pending writes, and any promises that are
26558
26867
  * awaiting a response from the server will not be resolved. If you have
@@ -26651,7 +26960,7 @@ function registerFirestore(variant, useFetchStreams = true) {
26651
26960
 
26652
26961
  /**
26653
26962
  * @license
26654
- * Copyright 2020 Google LLC
26963
+ * Copyright 2017 Google LLC
26655
26964
  *
26656
26965
  * Licensed under the Apache License, Version 2.0 (the "License");
26657
26966
  * you may not use this file except in compliance with the License.
@@ -26665,46 +26974,24 @@ function registerFirestore(variant, useFetchStreams = true) {
26665
26974
  * See the License for the specific language governing permissions and
26666
26975
  * limitations under the License.
26667
26976
  */
26977
+ function isPartialObserver(obj) {
26978
+ return implementsAnyMethods(obj, ['next', 'error', 'complete']);
26979
+ }
26668
26980
  /**
26669
- * A `FieldPath` refers to a field in a document. The path may consist of a
26670
- * single field name (referring to a top-level field in the document), or a
26671
- * list of field names (referring to a nested field in the document).
26672
- *
26673
- * Create a `FieldPath` by providing field names. If more than one field
26674
- * name is provided, the path will point to a nested field in a document.
26981
+ * Returns true if obj is an object and contains at least one of the specified
26982
+ * methods.
26675
26983
  */
26676
- class FieldPath {
26677
- /**
26678
- * Creates a `FieldPath` from the provided field names. If more than one field
26679
- * name is provided, the path will point to a nested field in a document.
26680
- *
26681
- * @param fieldNames - A list of field names.
26682
- */
26683
- constructor(...fieldNames) {
26684
- for (let i = 0; i < fieldNames.length; ++i) {
26685
- if (fieldNames[i].length === 0) {
26686
- throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` +
26687
- 'Field names must not be empty.');
26688
- }
26689
- }
26690
- this._internalPath = new FieldPath$1(fieldNames);
26984
+ function implementsAnyMethods(obj, methods) {
26985
+ if (typeof obj !== 'object' || obj === null) {
26986
+ return false;
26691
26987
  }
26692
- /**
26693
- * Returns true if this `FieldPath` is equal to the provided one.
26694
- *
26695
- * @param other - The `FieldPath` to compare against.
26696
- * @returns true if this `FieldPath` is equal to the provided one.
26697
- */
26698
- isEqual(other) {
26699
- return this._internalPath.isEqual(other._internalPath);
26988
+ const object = obj;
26989
+ for (const method of methods) {
26990
+ if (method in object && typeof object[method] === 'function') {
26991
+ return true;
26992
+ }
26700
26993
  }
26701
- }
26702
- /**
26703
- * Returns a special sentinel `FieldPath` to refer to the ID of a document.
26704
- * It can be used in queries to sort or filter by the document ID.
26705
- */
26706
- function documentId() {
26707
- return new FieldPath(DOCUMENT_KEY_NAME);
26994
+ return false;
26708
26995
  }
26709
26996
 
26710
26997
  /**
@@ -26805,11 +27092,69 @@ class Bytes {
26805
27092
  * limitations under the License.
26806
27093
  */
26807
27094
  /**
26808
- * Sentinel values that can be used when writing document fields with `set()`
26809
- * or `update()`.
26810
- */
26811
- class FieldValue {
26812
- /**
27095
+ * A `FieldPath` refers to a field in a document. The path may consist of a
27096
+ * single field name (referring to a top-level field in the document), or a
27097
+ * list of field names (referring to a nested field in the document).
27098
+ *
27099
+ * Create a `FieldPath` by providing field names. If more than one field
27100
+ * name is provided, the path will point to a nested field in a document.
27101
+ */
27102
+ class FieldPath {
27103
+ /**
27104
+ * Creates a `FieldPath` from the provided field names. If more than one field
27105
+ * name is provided, the path will point to a nested field in a document.
27106
+ *
27107
+ * @param fieldNames - A list of field names.
27108
+ */
27109
+ constructor(...fieldNames) {
27110
+ for (let i = 0; i < fieldNames.length; ++i) {
27111
+ if (fieldNames[i].length === 0) {
27112
+ throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` +
27113
+ 'Field names must not be empty.');
27114
+ }
27115
+ }
27116
+ this._internalPath = new FieldPath$1(fieldNames);
27117
+ }
27118
+ /**
27119
+ * Returns true if this `FieldPath` is equal to the provided one.
27120
+ *
27121
+ * @param other - The `FieldPath` to compare against.
27122
+ * @returns true if this `FieldPath` is equal to the provided one.
27123
+ */
27124
+ isEqual(other) {
27125
+ return this._internalPath.isEqual(other._internalPath);
27126
+ }
27127
+ }
27128
+ /**
27129
+ * Returns a special sentinel `FieldPath` to refer to the ID of a document.
27130
+ * It can be used in queries to sort or filter by the document ID.
27131
+ */
27132
+ function documentId() {
27133
+ return new FieldPath(DOCUMENT_KEY_NAME);
27134
+ }
27135
+
27136
+ /**
27137
+ * @license
27138
+ * Copyright 2020 Google LLC
27139
+ *
27140
+ * Licensed under the Apache License, Version 2.0 (the "License");
27141
+ * you may not use this file except in compliance with the License.
27142
+ * You may obtain a copy of the License at
27143
+ *
27144
+ * http://www.apache.org/licenses/LICENSE-2.0
27145
+ *
27146
+ * Unless required by applicable law or agreed to in writing, software
27147
+ * distributed under the License is distributed on an "AS IS" BASIS,
27148
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27149
+ * See the License for the specific language governing permissions and
27150
+ * limitations under the License.
27151
+ */
27152
+ /**
27153
+ * Sentinel values that can be used when writing document fields with `set()`
27154
+ * or `update()`.
27155
+ */
27156
+ class FieldValue {
27157
+ /**
26813
27158
  * @param _methodName - The public API endpoint that returns this class.
26814
27159
  * @hideconstructor
26815
27160
  */
@@ -27710,378 +28055,87 @@ function fieldPathFromArgument(methodName, arg) {
27710
28055
  * See the License for the specific language governing permissions and
27711
28056
  * limitations under the License.
27712
28057
  */
28058
+ function validateHasExplicitOrderByForLimitToLast(query) {
28059
+ if (query.limitType === "L" /* Last */ &&
28060
+ query.explicitOrderBy.length === 0) {
28061
+ throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
28062
+ }
28063
+ }
27713
28064
  /**
27714
- * Metadata about a snapshot, describing the state of the snapshot.
28065
+ * A `QueryConstraint` is used to narrow the set of documents returned by a
28066
+ * Firestore query. `QueryConstraint`s are created by invoking {@link where},
28067
+ * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
28068
+ * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and
28069
+ * can then be passed to {@link query} to create a new query instance that
28070
+ * also contains this `QueryConstraint`.
27715
28071
  */
27716
- class SnapshotMetadata {
27717
- /** @hideconstructor */
27718
- constructor(hasPendingWrites, fromCache) {
27719
- this.hasPendingWrites = hasPendingWrites;
27720
- this.fromCache = fromCache;
27721
- }
27722
- /**
27723
- * Returns true if this `SnapshotMetadata` is equal to the provided one.
27724
- *
27725
- * @param other - The `SnapshotMetadata` to compare against.
27726
- * @returns true if this `SnapshotMetadata` is equal to the provided one.
27727
- */
27728
- isEqual(other) {
27729
- return (this.hasPendingWrites === other.hasPendingWrites &&
27730
- this.fromCache === other.fromCache);
27731
- }
28072
+ class QueryConstraint {
27732
28073
  }
27733
28074
  /**
27734
- * A `DocumentSnapshot` contains data read from a document in your Firestore
27735
- * database. The data can be extracted with `.data()` or `.get(<field>)` to
27736
- * get a specific field.
28075
+ * Creates a new immutable instance of {@link Query} that is extended to also include
28076
+ * additional query constraints.
27737
28077
  *
27738
- * For a `DocumentSnapshot` that points to a non-existing document, any data
27739
- * access will return 'undefined'. You can use the `exists()` method to
27740
- * explicitly verify a document's existence.
28078
+ * @param query - The {@link Query} instance to use as a base for the new constraints.
28079
+ * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
28080
+ * @throws if any of the provided query constraints cannot be combined with the
28081
+ * existing or new constraints.
27741
28082
  */
27742
- class DocumentSnapshot extends DocumentSnapshot$1 {
27743
- /** @hideconstructor protected */
27744
- constructor(_firestore, userDataWriter, key, document, metadata, converter) {
27745
- super(_firestore, userDataWriter, key, document, converter);
27746
- this._firestore = _firestore;
27747
- this._firestoreImpl = _firestore;
27748
- this.metadata = metadata;
27749
- }
27750
- /**
27751
- * Returns whether or not the data exists. True if the document exists.
27752
- */
27753
- exists() {
27754
- return super.exists();
28083
+ function query(query, ...queryConstraints) {
28084
+ for (const constraint of queryConstraints) {
28085
+ query = constraint._apply(query);
27755
28086
  }
27756
- /**
27757
- * Retrieves all fields in the document as an `Object`. Returns `undefined` if
27758
- * the document doesn't exist.
27759
- *
27760
- * By default, `serverTimestamp()` values that have not yet been
27761
- * set to their final value will be returned as `null`. You can override
27762
- * this by passing an options object.
27763
- *
27764
- * @param options - An options object to configure how data is retrieved from
27765
- * the snapshot (for example the desired behavior for server timestamps that
27766
- * have not yet been set to their final value).
27767
- * @returns An `Object` containing all fields in the document or `undefined` if
27768
- * the document doesn't exist.
27769
- */
27770
- data(options = {}) {
27771
- if (!this._document) {
27772
- return undefined;
27773
- }
27774
- else if (this._converter) {
27775
- // We only want to use the converter and create a new DocumentSnapshot
27776
- // if a converter has been provided.
27777
- const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
27778
- /* converter= */ null);
27779
- return this._converter.fromFirestore(snapshot, options);
27780
- }
27781
- else {
27782
- return this._userDataWriter.convertValue(this._document.data.value, options.serverTimestamps);
27783
- }
28087
+ return query;
28088
+ }
28089
+ class QueryFilterConstraint extends QueryConstraint {
28090
+ constructor(_field, _op, _value) {
28091
+ super();
28092
+ this._field = _field;
28093
+ this._op = _op;
28094
+ this._value = _value;
28095
+ this.type = 'where';
27784
28096
  }
27785
- /**
27786
- * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
27787
- * document or field doesn't exist.
27788
- *
27789
- * By default, a `serverTimestamp()` that has not yet been set to
27790
- * its final value will be returned as `null`. You can override this by
27791
- * passing an options object.
27792
- *
27793
- * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
27794
- * field.
27795
- * @param options - An options object to configure how the field is retrieved
27796
- * from the snapshot (for example the desired behavior for server timestamps
27797
- * that have not yet been set to their final value).
27798
- * @returns The data at the specified field location or undefined if no such
27799
- * field exists in the document.
27800
- */
27801
- // We are using `any` here to avoid an explicit cast by our users.
27802
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
27803
- get(fieldPath, options = {}) {
27804
- if (this._document) {
27805
- const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));
27806
- if (value !== null) {
27807
- return this._userDataWriter.convertValue(value, options.serverTimestamps);
27808
- }
27809
- }
27810
- return undefined;
28097
+ _apply(query) {
28098
+ const reader = newUserDataReader(query.firestore);
28099
+ const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value);
28100
+ return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
27811
28101
  }
27812
28102
  }
27813
28103
  /**
27814
- * A `QueryDocumentSnapshot` contains data read from a document in your
27815
- * Firestore database as part of a query. The document is guaranteed to exist
27816
- * and its data can be extracted with `.data()` or `.get(<field>)` to get a
27817
- * specific field.
28104
+ * Creates a {@link QueryConstraint} that enforces that documents must contain the
28105
+ * specified field and that the value should satisfy the relation constraint
28106
+ * provided.
27818
28107
  *
27819
- * A `QueryDocumentSnapshot` offers the same API surface as a
27820
- * `DocumentSnapshot`. Since query results contain only existing documents, the
27821
- * `exists` property will always be true and `data()` will never return
27822
- * 'undefined'.
28108
+ * @param fieldPath - The path to compare
28109
+ * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
28110
+ * "&lt;=", "!=").
28111
+ * @param value - The value for comparison
28112
+ * @returns The created {@link Query}.
27823
28113
  */
27824
- class QueryDocumentSnapshot extends DocumentSnapshot {
27825
- /**
27826
- * Retrieves all fields in the document as an `Object`.
27827
- *
27828
- * By default, `serverTimestamp()` values that have not yet been
27829
- * set to their final value will be returned as `null`. You can override
27830
- * this by passing an options object.
27831
- *
27832
- * @override
27833
- * @param options - An options object to configure how data is retrieved from
27834
- * the snapshot (for example the desired behavior for server timestamps that
27835
- * have not yet been set to their final value).
27836
- * @returns An `Object` containing all fields in the document.
27837
- */
27838
- data(options = {}) {
27839
- return super.data(options);
28114
+ function where(fieldPath, opStr, value) {
28115
+ const op = opStr;
28116
+ const field = fieldPathFromArgument('where', fieldPath);
28117
+ return new QueryFilterConstraint(field, op, value);
28118
+ }
28119
+ class QueryOrderByConstraint extends QueryConstraint {
28120
+ constructor(_field, _direction) {
28121
+ super();
28122
+ this._field = _field;
28123
+ this._direction = _direction;
28124
+ this.type = 'orderBy';
28125
+ }
28126
+ _apply(query) {
28127
+ const orderBy = newQueryOrderBy(query._query, this._field, this._direction);
28128
+ return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy));
27840
28129
  }
27841
28130
  }
27842
28131
  /**
27843
- * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
27844
- * representing the results of a query. The documents can be accessed as an
27845
- * array via the `docs` property or enumerated using the `forEach` method. The
27846
- * number of documents can be determined via the `empty` and `size`
27847
- * properties.
27848
- */
27849
- class QuerySnapshot {
27850
- /** @hideconstructor */
27851
- constructor(_firestore, _userDataWriter, query, _snapshot) {
27852
- this._firestore = _firestore;
27853
- this._userDataWriter = _userDataWriter;
27854
- this._snapshot = _snapshot;
27855
- this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);
27856
- this.query = query;
27857
- }
27858
- /** An array of all the documents in the `QuerySnapshot`. */
27859
- get docs() {
27860
- const result = [];
27861
- this.forEach(doc => result.push(doc));
27862
- return result;
27863
- }
27864
- /** The number of documents in the `QuerySnapshot`. */
27865
- get size() {
27866
- return this._snapshot.docs.size;
27867
- }
27868
- /** True if there are no documents in the `QuerySnapshot`. */
27869
- get empty() {
27870
- return this.size === 0;
27871
- }
27872
- /**
27873
- * Enumerates all of the documents in the `QuerySnapshot`.
27874
- *
27875
- * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
27876
- * each document in the snapshot.
27877
- * @param thisArg - The `this` binding for the callback.
27878
- */
27879
- forEach(callback, thisArg) {
27880
- this._snapshot.docs.forEach(doc => {
27881
- callback.call(thisArg, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, doc.key, doc, new SnapshotMetadata(this._snapshot.mutatedKeys.has(doc.key), this._snapshot.fromCache), this.query.converter));
27882
- });
27883
- }
27884
- /**
27885
- * Returns an array of the documents changes since the last snapshot. If this
27886
- * is the first snapshot, all documents will be in the list as 'added'
27887
- * changes.
27888
- *
27889
- * @param options - `SnapshotListenOptions` that control whether metadata-only
27890
- * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
27891
- * snapshot events.
27892
- */
27893
- docChanges(options = {}) {
27894
- const includeMetadataChanges = !!options.includeMetadataChanges;
27895
- if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {
27896
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'To include metadata changes with your document changes, you must ' +
27897
- 'also pass { includeMetadataChanges:true } to onSnapshot().');
27898
- }
27899
- if (!this._cachedChanges ||
27900
- this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges) {
27901
- this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);
27902
- this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;
27903
- }
27904
- return this._cachedChanges;
27905
- }
27906
- }
27907
- /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
27908
- function changesFromSnapshot(querySnapshot, includeMetadataChanges) {
27909
- if (querySnapshot._snapshot.oldDocs.isEmpty()) {
27910
- let index = 0;
27911
- return querySnapshot._snapshot.docChanges.map(change => {
27912
- const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter);
27913
- return {
27914
- type: 'added',
27915
- doc,
27916
- oldIndex: -1,
27917
- newIndex: index++
27918
- };
27919
- });
27920
- }
27921
- else {
27922
- // A `DocumentSet` that is updated incrementally as changes are applied to use
27923
- // to lookup the index of a document.
27924
- let indexTracker = querySnapshot._snapshot.oldDocs;
27925
- return querySnapshot._snapshot.docChanges
27926
- .filter(change => includeMetadataChanges || change.type !== 3 /* Metadata */)
27927
- .map(change => {
27928
- const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter);
27929
- let oldIndex = -1;
27930
- let newIndex = -1;
27931
- if (change.type !== 0 /* Added */) {
27932
- oldIndex = indexTracker.indexOf(change.doc.key);
27933
- indexTracker = indexTracker.delete(change.doc.key);
27934
- }
27935
- if (change.type !== 1 /* Removed */) {
27936
- indexTracker = indexTracker.add(change.doc);
27937
- newIndex = indexTracker.indexOf(change.doc.key);
27938
- }
27939
- return {
27940
- type: resultChangeType(change.type),
27941
- doc,
27942
- oldIndex,
27943
- newIndex
27944
- };
27945
- });
27946
- }
27947
- }
27948
- function resultChangeType(type) {
27949
- switch (type) {
27950
- case 0 /* Added */:
27951
- return 'added';
27952
- case 2 /* Modified */:
27953
- case 3 /* Metadata */:
27954
- return 'modified';
27955
- case 1 /* Removed */:
27956
- return 'removed';
27957
- default:
27958
- return fail();
27959
- }
27960
- }
27961
- // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
27962
- // metadata
27963
- /**
27964
- * Returns true if the provided snapshots are equal.
27965
- *
27966
- * @param left - A snapshot to compare.
27967
- * @param right - A snapshot to compare.
27968
- * @returns true if the snapshots are equal.
27969
- */
27970
- function snapshotEqual(left, right) {
27971
- if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {
27972
- return (left._firestore === right._firestore &&
27973
- left._key.isEqual(right._key) &&
27974
- (left._document === null
27975
- ? right._document === null
27976
- : left._document.isEqual(right._document)) &&
27977
- left._converter === right._converter);
27978
- }
27979
- else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {
27980
- return (left._firestore === right._firestore &&
27981
- queryEqual(left.query, right.query) &&
27982
- left.metadata.isEqual(right.metadata) &&
27983
- left._snapshot.isEqual(right._snapshot));
27984
- }
27985
- return false;
27986
- }
27987
-
27988
- /**
27989
- * @license
27990
- * Copyright 2020 Google LLC
27991
- *
27992
- * Licensed under the Apache License, Version 2.0 (the "License");
27993
- * you may not use this file except in compliance with the License.
27994
- * You may obtain a copy of the License at
27995
- *
27996
- * http://www.apache.org/licenses/LICENSE-2.0
27997
- *
27998
- * Unless required by applicable law or agreed to in writing, software
27999
- * distributed under the License is distributed on an "AS IS" BASIS,
28000
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28001
- * See the License for the specific language governing permissions and
28002
- * limitations under the License.
28003
- */
28004
- function validateHasExplicitOrderByForLimitToLast(query) {
28005
- if (query.limitType === "L" /* Last */ &&
28006
- query.explicitOrderBy.length === 0) {
28007
- throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
28008
- }
28009
- }
28010
- /**
28011
- * A `QueryConstraint` is used to narrow the set of documents returned by a
28012
- * Firestore query. `QueryConstraint`s are created by invoking {@link where},
28013
- * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
28014
- * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and
28015
- * can then be passed to {@link query} to create a new query instance that
28016
- * also contains this `QueryConstraint`.
28017
- */
28018
- class QueryConstraint {
28019
- }
28020
- /**
28021
- * Creates a new immutable instance of {@link Query} that is extended to also include
28022
- * additional query constraints.
28023
- *
28024
- * @param query - The {@link Query} instance to use as a base for the new constraints.
28025
- * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
28026
- * @throws if any of the provided query constraints cannot be combined with the
28027
- * existing or new constraints.
28028
- */
28029
- function query(query, ...queryConstraints) {
28030
- for (const constraint of queryConstraints) {
28031
- query = constraint._apply(query);
28032
- }
28033
- return query;
28034
- }
28035
- class QueryFilterConstraint extends QueryConstraint {
28036
- constructor(_field, _op, _value) {
28037
- super();
28038
- this._field = _field;
28039
- this._op = _op;
28040
- this._value = _value;
28041
- this.type = 'where';
28042
- }
28043
- _apply(query) {
28044
- const reader = newUserDataReader(query.firestore);
28045
- const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value);
28046
- return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
28047
- }
28048
- }
28049
- /**
28050
- * Creates a {@link QueryConstraint} that enforces that documents must contain the
28051
- * specified field and that the value should satisfy the relation constraint
28052
- * provided.
28053
- *
28054
- * @param fieldPath - The path to compare
28055
- * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
28056
- * "&lt;=", "!=").
28057
- * @param value - The value for comparison
28058
- * @returns The created {@link Query}.
28059
- */
28060
- function where(fieldPath, opStr, value) {
28061
- const op = opStr;
28062
- const field = fieldPathFromArgument('where', fieldPath);
28063
- return new QueryFilterConstraint(field, op, value);
28064
- }
28065
- class QueryOrderByConstraint extends QueryConstraint {
28066
- constructor(_field, _direction) {
28067
- super();
28068
- this._field = _field;
28069
- this._direction = _direction;
28070
- this.type = 'orderBy';
28071
- }
28072
- _apply(query) {
28073
- const orderBy = newQueryOrderBy(query._query, this._field, this._direction);
28074
- return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy));
28075
- }
28076
- }
28077
- /**
28078
- * Creates a {@link QueryConstraint} that sorts the query result by the
28079
- * specified field, optionally in descending order instead of ascending.
28080
- *
28081
- * @param fieldPath - The field to sort by.
28082
- * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
28083
- * not specified, order will be ascending.
28084
- * @returns The created {@link Query}.
28132
+ * Creates a {@link QueryConstraint} that sorts the query result by the
28133
+ * specified field, optionally in descending order instead of ascending.
28134
+ *
28135
+ * @param fieldPath - The field to sort by.
28136
+ * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
28137
+ * not specified, order will be ascending.
28138
+ * @returns The created {@link Query}.
28085
28139
  */
28086
28140
  function orderBy(fieldPath, directionStr = 'asc') {
28087
28141
  const direction = directionStr;
@@ -28445,31 +28499,6 @@ function validateOrderByAndInequalityMatch(baseQuery, inequality, orderBy) {
28445
28499
  }
28446
28500
  }
28447
28501
 
28448
- /**
28449
- * @license
28450
- * Copyright 2022 Google LLC
28451
- *
28452
- * Licensed under the Apache License, Version 2.0 (the "License");
28453
- * you may not use this file except in compliance with the License.
28454
- * You may obtain a copy of the License at
28455
- *
28456
- * http://www.apache.org/licenses/LICENSE-2.0
28457
- *
28458
- * Unless required by applicable law or agreed to in writing, software
28459
- * distributed under the License is distributed on an "AS IS" BASIS,
28460
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28461
- * See the License for the specific language governing permissions and
28462
- * limitations under the License.
28463
- */
28464
- const DEFAULT_TRANSACTION_OPTIONS = {
28465
- maxAttempts: 5
28466
- };
28467
- function validateTransactionOptions(options) {
28468
- if (options.maxAttempts < 1) {
28469
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1');
28470
- }
28471
- }
28472
-
28473
28502
  /**
28474
28503
  * @license
28475
28504
  * Copyright 2020 Google LLC
@@ -28644,221 +28673,276 @@ class LiteUserDataWriter extends AbstractUserDataWriter {
28644
28673
  * limitations under the License.
28645
28674
  */
28646
28675
  /**
28647
- * A write batch, used to perform multiple writes as a single atomic unit.
28648
- *
28649
- * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
28650
- * provides methods for adding writes to the write batch. None of the writes
28651
- * will be committed (or visible locally) until {@link WriteBatch.commit} is
28652
- * called.
28676
+ * Metadata about a snapshot, describing the state of the snapshot.
28653
28677
  */
28654
- class WriteBatch {
28678
+ class SnapshotMetadata {
28655
28679
  /** @hideconstructor */
28656
- constructor(_firestore, _commitHandler) {
28657
- this._firestore = _firestore;
28658
- this._commitHandler = _commitHandler;
28659
- this._mutations = [];
28660
- this._committed = false;
28661
- this._dataReader = newUserDataReader(_firestore);
28680
+ constructor(hasPendingWrites, fromCache) {
28681
+ this.hasPendingWrites = hasPendingWrites;
28682
+ this.fromCache = fromCache;
28662
28683
  }
28663
- set(documentRef, data, options) {
28664
- this._verifyNotCommitted();
28665
- const ref = validateReference(documentRef, this._firestore);
28666
- const convertedValue = applyFirestoreDataConverter(ref.converter, data, options);
28667
- const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options);
28668
- this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));
28669
- return this;
28684
+ /**
28685
+ * Returns true if this `SnapshotMetadata` is equal to the provided one.
28686
+ *
28687
+ * @param other - The `SnapshotMetadata` to compare against.
28688
+ * @returns true if this `SnapshotMetadata` is equal to the provided one.
28689
+ */
28690
+ isEqual(other) {
28691
+ return (this.hasPendingWrites === other.hasPendingWrites &&
28692
+ this.fromCache === other.fromCache);
28670
28693
  }
28671
- update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
28672
- this._verifyNotCommitted();
28673
- const ref = validateReference(documentRef, this._firestore);
28674
- // For Compat types, we have to "extract" the underlying types before
28675
- // performing validation.
28676
- fieldOrUpdateData = util$1.getModularInstance(fieldOrUpdateData);
28677
- let parsed;
28678
- if (typeof fieldOrUpdateData === 'string' ||
28679
- fieldOrUpdateData instanceof FieldPath) {
28680
- parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
28681
- }
28682
- else {
28683
- parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData);
28684
- }
28685
- this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true)));
28686
- return this;
28694
+ }
28695
+ /**
28696
+ * A `DocumentSnapshot` contains data read from a document in your Firestore
28697
+ * database. The data can be extracted with `.data()` or `.get(<field>)` to
28698
+ * get a specific field.
28699
+ *
28700
+ * For a `DocumentSnapshot` that points to a non-existing document, any data
28701
+ * access will return 'undefined'. You can use the `exists()` method to
28702
+ * explicitly verify a document's existence.
28703
+ */
28704
+ class DocumentSnapshot extends DocumentSnapshot$1 {
28705
+ /** @hideconstructor protected */
28706
+ constructor(_firestore, userDataWriter, key, document, metadata, converter) {
28707
+ super(_firestore, userDataWriter, key, document, converter);
28708
+ this._firestore = _firestore;
28709
+ this._firestoreImpl = _firestore;
28710
+ this.metadata = metadata;
28687
28711
  }
28688
28712
  /**
28689
- * Deletes the document referred to by the provided {@link DocumentReference}.
28690
- *
28691
- * @param documentRef - A reference to the document to be deleted.
28692
- * @returns This `WriteBatch` instance. Used for chaining method calls.
28713
+ * Returns whether or not the data exists. True if the document exists.
28693
28714
  */
28694
- delete(documentRef) {
28695
- this._verifyNotCommitted();
28696
- const ref = validateReference(documentRef, this._firestore);
28697
- this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none()));
28698
- return this;
28715
+ exists() {
28716
+ return super.exists();
28699
28717
  }
28700
28718
  /**
28701
- * Commits all of the writes in this write batch as a single atomic unit.
28719
+ * Retrieves all fields in the document as an `Object`. Returns `undefined` if
28720
+ * the document doesn't exist.
28702
28721
  *
28703
- * The result of these writes will only be reflected in document reads that
28704
- * occur after the returned promise resolves. If the client is offline, the
28705
- * write fails. If you would like to see local modifications or buffer writes
28706
- * until the client is online, use the full Firestore SDK.
28722
+ * By default, `serverTimestamp()` values that have not yet been
28723
+ * set to their final value will be returned as `null`. You can override
28724
+ * this by passing an options object.
28707
28725
  *
28708
- * @returns A `Promise` resolved once all of the writes in the batch have been
28709
- * successfully written to the backend as an atomic unit (note that it won't
28710
- * resolve while you're offline).
28726
+ * @param options - An options object to configure how data is retrieved from
28727
+ * the snapshot (for example the desired behavior for server timestamps that
28728
+ * have not yet been set to their final value).
28729
+ * @returns An `Object` containing all fields in the document or `undefined` if
28730
+ * the document doesn't exist.
28711
28731
  */
28712
- commit() {
28713
- this._verifyNotCommitted();
28714
- this._committed = true;
28715
- if (this._mutations.length > 0) {
28716
- return this._commitHandler(this._mutations);
28732
+ data(options = {}) {
28733
+ if (!this._document) {
28734
+ return undefined;
28735
+ }
28736
+ else if (this._converter) {
28737
+ // We only want to use the converter and create a new DocumentSnapshot
28738
+ // if a converter has been provided.
28739
+ const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
28740
+ /* converter= */ null);
28741
+ return this._converter.fromFirestore(snapshot, options);
28742
+ }
28743
+ else {
28744
+ return this._userDataWriter.convertValue(this._document.data.value, options.serverTimestamps);
28717
28745
  }
28718
- return Promise.resolve();
28719
28746
  }
28720
- _verifyNotCommitted() {
28721
- if (this._committed) {
28722
- throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +
28723
- 'has been called.');
28747
+ /**
28748
+ * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
28749
+ * document or field doesn't exist.
28750
+ *
28751
+ * By default, a `serverTimestamp()` that has not yet been set to
28752
+ * its final value will be returned as `null`. You can override this by
28753
+ * passing an options object.
28754
+ *
28755
+ * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
28756
+ * field.
28757
+ * @param options - An options object to configure how the field is retrieved
28758
+ * from the snapshot (for example the desired behavior for server timestamps
28759
+ * that have not yet been set to their final value).
28760
+ * @returns The data at the specified field location or undefined if no such
28761
+ * field exists in the document.
28762
+ */
28763
+ // We are using `any` here to avoid an explicit cast by our users.
28764
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28765
+ get(fieldPath, options = {}) {
28766
+ if (this._document) {
28767
+ const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));
28768
+ if (value !== null) {
28769
+ return this._userDataWriter.convertValue(value, options.serverTimestamps);
28770
+ }
28724
28771
  }
28772
+ return undefined;
28725
28773
  }
28726
28774
  }
28727
- function validateReference(documentRef, firestore) {
28728
- documentRef = util$1.getModularInstance(documentRef);
28729
- if (documentRef.firestore !== firestore) {
28730
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');
28731
- }
28732
- else {
28733
- return documentRef;
28734
- }
28735
- }
28736
-
28737
28775
  /**
28738
- * @license
28739
- * Copyright 2020 Google LLC
28740
- *
28741
- * Licensed under the Apache License, Version 2.0 (the "License");
28742
- * you may not use this file except in compliance with the License.
28743
- * You may obtain a copy of the License at
28744
- *
28745
- * http://www.apache.org/licenses/LICENSE-2.0
28776
+ * A `QueryDocumentSnapshot` contains data read from a document in your
28777
+ * Firestore database as part of a query. The document is guaranteed to exist
28778
+ * and its data can be extracted with `.data()` or `.get(<field>)` to get a
28779
+ * specific field.
28746
28780
  *
28747
- * Unless required by applicable law or agreed to in writing, software
28748
- * distributed under the License is distributed on an "AS IS" BASIS,
28749
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28750
- * See the License for the specific language governing permissions and
28751
- * limitations under the License.
28781
+ * A `QueryDocumentSnapshot` offers the same API surface as a
28782
+ * `DocumentSnapshot`. Since query results contain only existing documents, the
28783
+ * `exists` property will always be true and `data()` will never return
28784
+ * 'undefined'.
28752
28785
  */
28753
- // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
28754
- // legacy SDK.
28786
+ class QueryDocumentSnapshot extends DocumentSnapshot {
28787
+ /**
28788
+ * Retrieves all fields in the document as an `Object`.
28789
+ *
28790
+ * By default, `serverTimestamp()` values that have not yet been
28791
+ * set to their final value will be returned as `null`. You can override
28792
+ * this by passing an options object.
28793
+ *
28794
+ * @override
28795
+ * @param options - An options object to configure how data is retrieved from
28796
+ * the snapshot (for example the desired behavior for server timestamps that
28797
+ * have not yet been set to their final value).
28798
+ * @returns An `Object` containing all fields in the document.
28799
+ */
28800
+ data(options = {}) {
28801
+ return super.data(options);
28802
+ }
28803
+ }
28755
28804
  /**
28756
- * A reference to a transaction.
28757
- *
28758
- * The `Transaction` object passed to a transaction's `updateFunction` provides
28759
- * the methods to read and write data within the transaction context. See
28760
- * {@link runTransaction}.
28805
+ * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
28806
+ * representing the results of a query. The documents can be accessed as an
28807
+ * array via the `docs` property or enumerated using the `forEach` method. The
28808
+ * number of documents can be determined via the `empty` and `size`
28809
+ * properties.
28761
28810
  */
28762
- class Transaction$1 {
28811
+ class QuerySnapshot {
28763
28812
  /** @hideconstructor */
28764
- constructor(_firestore, _transaction) {
28813
+ constructor(_firestore, _userDataWriter, query, _snapshot) {
28765
28814
  this._firestore = _firestore;
28766
- this._transaction = _transaction;
28767
- this._dataReader = newUserDataReader(_firestore);
28815
+ this._userDataWriter = _userDataWriter;
28816
+ this._snapshot = _snapshot;
28817
+ this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);
28818
+ this.query = query;
28819
+ }
28820
+ /** An array of all the documents in the `QuerySnapshot`. */
28821
+ get docs() {
28822
+ const result = [];
28823
+ this.forEach(doc => result.push(doc));
28824
+ return result;
28825
+ }
28826
+ /** The number of documents in the `QuerySnapshot`. */
28827
+ get size() {
28828
+ return this._snapshot.docs.size;
28829
+ }
28830
+ /** True if there are no documents in the `QuerySnapshot`. */
28831
+ get empty() {
28832
+ return this.size === 0;
28768
28833
  }
28769
28834
  /**
28770
- * Reads the document referenced by the provided {@link DocumentReference}.
28835
+ * Enumerates all of the documents in the `QuerySnapshot`.
28771
28836
  *
28772
- * @param documentRef - A reference to the document to be read.
28773
- * @returns A `DocumentSnapshot` with the read data.
28837
+ * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
28838
+ * each document in the snapshot.
28839
+ * @param thisArg - The `this` binding for the callback.
28774
28840
  */
28775
- get(documentRef) {
28776
- const ref = validateReference(documentRef, this._firestore);
28777
- const userDataWriter = new LiteUserDataWriter(this._firestore);
28778
- return this._transaction.lookup([ref._key]).then(docs => {
28779
- if (!docs || docs.length !== 1) {
28780
- return fail();
28781
- }
28782
- const doc = docs[0];
28783
- if (doc.isFoundDocument()) {
28784
- return new DocumentSnapshot$1(this._firestore, userDataWriter, doc.key, doc, ref.converter);
28785
- }
28786
- else if (doc.isNoDocument()) {
28787
- return new DocumentSnapshot$1(this._firestore, userDataWriter, ref._key, null, ref.converter);
28788
- }
28789
- else {
28790
- throw fail();
28791
- }
28841
+ forEach(callback, thisArg) {
28842
+ this._snapshot.docs.forEach(doc => {
28843
+ callback.call(thisArg, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, doc.key, doc, new SnapshotMetadata(this._snapshot.mutatedKeys.has(doc.key), this._snapshot.fromCache), this.query.converter));
28792
28844
  });
28793
28845
  }
28794
- set(documentRef, value, options) {
28795
- const ref = validateReference(documentRef, this._firestore);
28796
- const convertedValue = applyFirestoreDataConverter(ref.converter, value, options);
28797
- const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options);
28798
- this._transaction.set(ref._key, parsed);
28799
- return this;
28800
- }
28801
- update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
28802
- const ref = validateReference(documentRef, this._firestore);
28803
- // For Compat types, we have to "extract" the underlying types before
28804
- // performing validation.
28805
- fieldOrUpdateData = util$1.getModularInstance(fieldOrUpdateData);
28806
- let parsed;
28807
- if (typeof fieldOrUpdateData === 'string' ||
28808
- fieldOrUpdateData instanceof FieldPath) {
28809
- parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
28810
- }
28811
- else {
28812
- parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData);
28813
- }
28814
- this._transaction.update(ref._key, parsed);
28815
- return this;
28816
- }
28817
28846
  /**
28818
- * Deletes the document referred to by the provided {@link DocumentReference}.
28847
+ * Returns an array of the documents changes since the last snapshot. If this
28848
+ * is the first snapshot, all documents will be in the list as 'added'
28849
+ * changes.
28819
28850
  *
28820
- * @param documentRef - A reference to the document to be deleted.
28821
- * @returns This `Transaction` instance. Used for chaining method calls.
28851
+ * @param options - `SnapshotListenOptions` that control whether metadata-only
28852
+ * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
28853
+ * snapshot events.
28822
28854
  */
28823
- delete(documentRef) {
28824
- const ref = validateReference(documentRef, this._firestore);
28825
- this._transaction.delete(ref._key);
28826
- return this;
28855
+ docChanges(options = {}) {
28856
+ const includeMetadataChanges = !!options.includeMetadataChanges;
28857
+ if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {
28858
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'To include metadata changes with your document changes, you must ' +
28859
+ 'also pass { includeMetadataChanges:true } to onSnapshot().');
28860
+ }
28861
+ if (!this._cachedChanges ||
28862
+ this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges) {
28863
+ this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);
28864
+ this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;
28865
+ }
28866
+ return this._cachedChanges;
28867
+ }
28868
+ }
28869
+ /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
28870
+ function changesFromSnapshot(querySnapshot, includeMetadataChanges) {
28871
+ if (querySnapshot._snapshot.oldDocs.isEmpty()) {
28872
+ let index = 0;
28873
+ return querySnapshot._snapshot.docChanges.map(change => {
28874
+ const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter);
28875
+ return {
28876
+ type: 'added',
28877
+ doc,
28878
+ oldIndex: -1,
28879
+ newIndex: index++
28880
+ };
28881
+ });
28882
+ }
28883
+ else {
28884
+ // A `DocumentSet` that is updated incrementally as changes are applied to use
28885
+ // to lookup the index of a document.
28886
+ let indexTracker = querySnapshot._snapshot.oldDocs;
28887
+ return querySnapshot._snapshot.docChanges
28888
+ .filter(change => includeMetadataChanges || change.type !== 3 /* Metadata */)
28889
+ .map(change => {
28890
+ const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter);
28891
+ let oldIndex = -1;
28892
+ let newIndex = -1;
28893
+ if (change.type !== 0 /* Added */) {
28894
+ oldIndex = indexTracker.indexOf(change.doc.key);
28895
+ indexTracker = indexTracker.delete(change.doc.key);
28896
+ }
28897
+ if (change.type !== 1 /* Removed */) {
28898
+ indexTracker = indexTracker.add(change.doc);
28899
+ newIndex = indexTracker.indexOf(change.doc.key);
28900
+ }
28901
+ return {
28902
+ type: resultChangeType(change.type),
28903
+ doc,
28904
+ oldIndex,
28905
+ newIndex
28906
+ };
28907
+ });
28908
+ }
28909
+ }
28910
+ function resultChangeType(type) {
28911
+ switch (type) {
28912
+ case 0 /* Added */:
28913
+ return 'added';
28914
+ case 2 /* Modified */:
28915
+ case 3 /* Metadata */:
28916
+ return 'modified';
28917
+ case 1 /* Removed */:
28918
+ return 'removed';
28919
+ default:
28920
+ return fail();
28827
28921
  }
28828
- }
28829
-
28830
- /**
28831
- * @license
28832
- * Copyright 2017 Google LLC
28833
- *
28834
- * Licensed under the Apache License, Version 2.0 (the "License");
28835
- * you may not use this file except in compliance with the License.
28836
- * You may obtain a copy of the License at
28837
- *
28838
- * http://www.apache.org/licenses/LICENSE-2.0
28839
- *
28840
- * Unless required by applicable law or agreed to in writing, software
28841
- * distributed under the License is distributed on an "AS IS" BASIS,
28842
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28843
- * See the License for the specific language governing permissions and
28844
- * limitations under the License.
28845
- */
28846
- function isPartialObserver(obj) {
28847
- return implementsAnyMethods(obj, ['next', 'error', 'complete']);
28848
28922
  }
28923
+ // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
28924
+ // metadata
28849
28925
  /**
28850
- * Returns true if obj is an object and contains at least one of the specified
28851
- * methods.
28926
+ * Returns true if the provided snapshots are equal.
28927
+ *
28928
+ * @param left - A snapshot to compare.
28929
+ * @param right - A snapshot to compare.
28930
+ * @returns true if the snapshots are equal.
28852
28931
  */
28853
- function implementsAnyMethods(obj, methods) {
28854
- if (typeof obj !== 'object' || obj === null) {
28855
- return false;
28932
+ function snapshotEqual(left, right) {
28933
+ if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {
28934
+ return (left._firestore === right._firestore &&
28935
+ left._key.isEqual(right._key) &&
28936
+ (left._document === null
28937
+ ? right._document === null
28938
+ : left._document.isEqual(right._document)) &&
28939
+ left._converter === right._converter);
28856
28940
  }
28857
- const object = obj;
28858
- for (const method of methods) {
28859
- if (method in object && typeof object[method] === 'function') {
28860
- return true;
28861
- }
28941
+ else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {
28942
+ return (left._firestore === right._firestore &&
28943
+ queryEqual(left.query, right.query) &&
28944
+ left.metadata.isEqual(right.metadata) &&
28945
+ left._snapshot.isEqual(right._snapshot));
28862
28946
  }
28863
28947
  return false;
28864
28948
  }
@@ -29127,6 +29211,307 @@ function convertToDocSnapshot(firestore, ref, snapshot) {
29127
29211
  return new DocumentSnapshot(firestore, userDataWriter, ref._key, doc, new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache), ref.converter);
29128
29212
  }
29129
29213
 
29214
+ /**
29215
+ * @license
29216
+ * Copyright 2022 Google LLC
29217
+ *
29218
+ * Licensed under the Apache License, Version 2.0 (the "License");
29219
+ * you may not use this file except in compliance with the License.
29220
+ * You may obtain a copy of the License at
29221
+ *
29222
+ * http://www.apache.org/licenses/LICENSE-2.0
29223
+ *
29224
+ * Unless required by applicable law or agreed to in writing, software
29225
+ * distributed under the License is distributed on an "AS IS" BASIS,
29226
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29227
+ * See the License for the specific language governing permissions and
29228
+ * limitations under the License.
29229
+ */
29230
+ /**
29231
+ * Compares two `AggregateQuerySnapshot` instances for equality.
29232
+ *
29233
+ * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
29234
+ * underlying queries that compare equal, and the same data.
29235
+ *
29236
+ * @param left - The first `AggregateQuerySnapshot` to compare.
29237
+ * @param right - The second `AggregateQuerySnapshot` to compare.
29238
+ *
29239
+ * @returns `true` if the objects are "equal", as defined above, or `false`
29240
+ * otherwise.
29241
+ */
29242
+ function aggregateQuerySnapshotEqual(left, right) {
29243
+ return (queryEqual(left.query, right.query) && util$1.deepEqual(left.data(), right.data()));
29244
+ }
29245
+
29246
+ /**
29247
+ * @license
29248
+ * Copyright 2022 Google LLC
29249
+ *
29250
+ * Licensed under the Apache License, Version 2.0 (the "License");
29251
+ * you may not use this file except in compliance with the License.
29252
+ * You may obtain a copy of the License at
29253
+ *
29254
+ * http://www.apache.org/licenses/LICENSE-2.0
29255
+ *
29256
+ * Unless required by applicable law or agreed to in writing, software
29257
+ * distributed under the License is distributed on an "AS IS" BASIS,
29258
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29259
+ * See the License for the specific language governing permissions and
29260
+ * limitations under the License.
29261
+ */
29262
+ /**
29263
+ * Calculates the number of documents in the result set of the given query,
29264
+ * without actually downloading the documents.
29265
+ *
29266
+ * Using this function to count the documents is efficient because only the
29267
+ * final count, not the documents' data, is downloaded. This function can even
29268
+ * count the documents if the result set would be prohibitively large to
29269
+ * download entirely (e.g. thousands of documents).
29270
+ *
29271
+ * The result received from the server is presented, unaltered, without
29272
+ * considering any local state. That is, documents in the local cache are not
29273
+ * taken into consideration, neither are local modifications not yet
29274
+ * synchronized with the server. Previously-downloaded results, if any, are not
29275
+ * used: every request using this source necessarily involves a round trip to
29276
+ * the server.
29277
+ *
29278
+ * @param query - The query whose result set size to calculate.
29279
+ * @returns A Promise that will be resolved with the count; the count can be
29280
+ * retrieved from `snapshot.data().count`, where `snapshot` is the
29281
+ * `AggregateQuerySnapshot` to which the returned Promise resolves.
29282
+ */
29283
+ function getCountFromServer(query) {
29284
+ const firestore = cast(query.firestore, Firestore);
29285
+ const client = ensureFirestoreConfigured(firestore);
29286
+ const userDataWriter = new ExpUserDataWriter(firestore);
29287
+ return firestoreClientRunCountQuery(client, query, userDataWriter);
29288
+ }
29289
+
29290
+ /**
29291
+ * @license
29292
+ * Copyright 2022 Google LLC
29293
+ *
29294
+ * Licensed under the Apache License, Version 2.0 (the "License");
29295
+ * you may not use this file except in compliance with the License.
29296
+ * You may obtain a copy of the License at
29297
+ *
29298
+ * http://www.apache.org/licenses/LICENSE-2.0
29299
+ *
29300
+ * Unless required by applicable law or agreed to in writing, software
29301
+ * distributed under the License is distributed on an "AS IS" BASIS,
29302
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29303
+ * See the License for the specific language governing permissions and
29304
+ * limitations under the License.
29305
+ */
29306
+ const DEFAULT_TRANSACTION_OPTIONS = {
29307
+ maxAttempts: 5
29308
+ };
29309
+ function validateTransactionOptions(options) {
29310
+ if (options.maxAttempts < 1) {
29311
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1');
29312
+ }
29313
+ }
29314
+
29315
+ /**
29316
+ * @license
29317
+ * Copyright 2020 Google LLC
29318
+ *
29319
+ * Licensed under the Apache License, Version 2.0 (the "License");
29320
+ * you may not use this file except in compliance with the License.
29321
+ * You may obtain a copy of the License at
29322
+ *
29323
+ * http://www.apache.org/licenses/LICENSE-2.0
29324
+ *
29325
+ * Unless required by applicable law or agreed to in writing, software
29326
+ * distributed under the License is distributed on an "AS IS" BASIS,
29327
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29328
+ * See the License for the specific language governing permissions and
29329
+ * limitations under the License.
29330
+ */
29331
+ /**
29332
+ * A write batch, used to perform multiple writes as a single atomic unit.
29333
+ *
29334
+ * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
29335
+ * provides methods for adding writes to the write batch. None of the writes
29336
+ * will be committed (or visible locally) until {@link WriteBatch.commit} is
29337
+ * called.
29338
+ */
29339
+ class WriteBatch {
29340
+ /** @hideconstructor */
29341
+ constructor(_firestore, _commitHandler) {
29342
+ this._firestore = _firestore;
29343
+ this._commitHandler = _commitHandler;
29344
+ this._mutations = [];
29345
+ this._committed = false;
29346
+ this._dataReader = newUserDataReader(_firestore);
29347
+ }
29348
+ set(documentRef, data, options) {
29349
+ this._verifyNotCommitted();
29350
+ const ref = validateReference(documentRef, this._firestore);
29351
+ const convertedValue = applyFirestoreDataConverter(ref.converter, data, options);
29352
+ const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options);
29353
+ this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));
29354
+ return this;
29355
+ }
29356
+ update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
29357
+ this._verifyNotCommitted();
29358
+ const ref = validateReference(documentRef, this._firestore);
29359
+ // For Compat types, we have to "extract" the underlying types before
29360
+ // performing validation.
29361
+ fieldOrUpdateData = util$1.getModularInstance(fieldOrUpdateData);
29362
+ let parsed;
29363
+ if (typeof fieldOrUpdateData === 'string' ||
29364
+ fieldOrUpdateData instanceof FieldPath) {
29365
+ parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
29366
+ }
29367
+ else {
29368
+ parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData);
29369
+ }
29370
+ this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true)));
29371
+ return this;
29372
+ }
29373
+ /**
29374
+ * Deletes the document referred to by the provided {@link DocumentReference}.
29375
+ *
29376
+ * @param documentRef - A reference to the document to be deleted.
29377
+ * @returns This `WriteBatch` instance. Used for chaining method calls.
29378
+ */
29379
+ delete(documentRef) {
29380
+ this._verifyNotCommitted();
29381
+ const ref = validateReference(documentRef, this._firestore);
29382
+ this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none()));
29383
+ return this;
29384
+ }
29385
+ /**
29386
+ * Commits all of the writes in this write batch as a single atomic unit.
29387
+ *
29388
+ * The result of these writes will only be reflected in document reads that
29389
+ * occur after the returned promise resolves. If the client is offline, the
29390
+ * write fails. If you would like to see local modifications or buffer writes
29391
+ * until the client is online, use the full Firestore SDK.
29392
+ *
29393
+ * @returns A `Promise` resolved once all of the writes in the batch have been
29394
+ * successfully written to the backend as an atomic unit (note that it won't
29395
+ * resolve while you're offline).
29396
+ */
29397
+ commit() {
29398
+ this._verifyNotCommitted();
29399
+ this._committed = true;
29400
+ if (this._mutations.length > 0) {
29401
+ return this._commitHandler(this._mutations);
29402
+ }
29403
+ return Promise.resolve();
29404
+ }
29405
+ _verifyNotCommitted() {
29406
+ if (this._committed) {
29407
+ throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +
29408
+ 'has been called.');
29409
+ }
29410
+ }
29411
+ }
29412
+ function validateReference(documentRef, firestore) {
29413
+ documentRef = util$1.getModularInstance(documentRef);
29414
+ if (documentRef.firestore !== firestore) {
29415
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');
29416
+ }
29417
+ else {
29418
+ return documentRef;
29419
+ }
29420
+ }
29421
+
29422
+ /**
29423
+ * @license
29424
+ * Copyright 2020 Google LLC
29425
+ *
29426
+ * Licensed under the Apache License, Version 2.0 (the "License");
29427
+ * you may not use this file except in compliance with the License.
29428
+ * You may obtain a copy of the License at
29429
+ *
29430
+ * http://www.apache.org/licenses/LICENSE-2.0
29431
+ *
29432
+ * Unless required by applicable law or agreed to in writing, software
29433
+ * distributed under the License is distributed on an "AS IS" BASIS,
29434
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29435
+ * See the License for the specific language governing permissions and
29436
+ * limitations under the License.
29437
+ */
29438
+ // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
29439
+ // legacy SDK.
29440
+ /**
29441
+ * A reference to a transaction.
29442
+ *
29443
+ * The `Transaction` object passed to a transaction's `updateFunction` provides
29444
+ * the methods to read and write data within the transaction context. See
29445
+ * {@link runTransaction}.
29446
+ */
29447
+ class Transaction$1 {
29448
+ /** @hideconstructor */
29449
+ constructor(_firestore, _transaction) {
29450
+ this._firestore = _firestore;
29451
+ this._transaction = _transaction;
29452
+ this._dataReader = newUserDataReader(_firestore);
29453
+ }
29454
+ /**
29455
+ * Reads the document referenced by the provided {@link DocumentReference}.
29456
+ *
29457
+ * @param documentRef - A reference to the document to be read.
29458
+ * @returns A `DocumentSnapshot` with the read data.
29459
+ */
29460
+ get(documentRef) {
29461
+ const ref = validateReference(documentRef, this._firestore);
29462
+ const userDataWriter = new LiteUserDataWriter(this._firestore);
29463
+ return this._transaction.lookup([ref._key]).then(docs => {
29464
+ if (!docs || docs.length !== 1) {
29465
+ return fail();
29466
+ }
29467
+ const doc = docs[0];
29468
+ if (doc.isFoundDocument()) {
29469
+ return new DocumentSnapshot$1(this._firestore, userDataWriter, doc.key, doc, ref.converter);
29470
+ }
29471
+ else if (doc.isNoDocument()) {
29472
+ return new DocumentSnapshot$1(this._firestore, userDataWriter, ref._key, null, ref.converter);
29473
+ }
29474
+ else {
29475
+ throw fail();
29476
+ }
29477
+ });
29478
+ }
29479
+ set(documentRef, value, options) {
29480
+ const ref = validateReference(documentRef, this._firestore);
29481
+ const convertedValue = applyFirestoreDataConverter(ref.converter, value, options);
29482
+ const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options);
29483
+ this._transaction.set(ref._key, parsed);
29484
+ return this;
29485
+ }
29486
+ update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
29487
+ const ref = validateReference(documentRef, this._firestore);
29488
+ // For Compat types, we have to "extract" the underlying types before
29489
+ // performing validation.
29490
+ fieldOrUpdateData = util$1.getModularInstance(fieldOrUpdateData);
29491
+ let parsed;
29492
+ if (typeof fieldOrUpdateData === 'string' ||
29493
+ fieldOrUpdateData instanceof FieldPath) {
29494
+ parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
29495
+ }
29496
+ else {
29497
+ parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData);
29498
+ }
29499
+ this._transaction.update(ref._key, parsed);
29500
+ return this;
29501
+ }
29502
+ /**
29503
+ * Deletes the document referred to by the provided {@link DocumentReference}.
29504
+ *
29505
+ * @param documentRef - A reference to the document to be deleted.
29506
+ * @returns This `Transaction` instance. Used for chaining method calls.
29507
+ */
29508
+ delete(documentRef) {
29509
+ const ref = validateReference(documentRef, this._firestore);
29510
+ this._transaction.delete(ref._key);
29511
+ return this;
29512
+ }
29513
+ }
29514
+
29130
29515
  /**
29131
29516
  * @license
29132
29517
  * Copyright 2020 Google LLC
@@ -29413,6 +29798,8 @@ function tryGetString(data, property) {
29413
29798
  registerFirestore('node');
29414
29799
 
29415
29800
  exports.AbstractUserDataWriter = AbstractUserDataWriter;
29801
+ exports.AggregateField = AggregateField;
29802
+ exports.AggregateQuerySnapshot = AggregateQuerySnapshot;
29416
29803
  exports.Bytes = Bytes;
29417
29804
  exports.CACHE_SIZE_UNLIMITED = CACHE_SIZE_UNLIMITED;
29418
29805
  exports.CollectionReference = CollectionReference;
@@ -29443,6 +29830,7 @@ exports._isBase64Available = isBase64Available;
29443
29830
  exports._logWarn = logWarn;
29444
29831
  exports._validateIsNotUsedTogether = validateIsNotUsedTogether;
29445
29832
  exports.addDoc = addDoc;
29833
+ exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual;
29446
29834
  exports.arrayRemove = arrayRemove;
29447
29835
  exports.arrayUnion = arrayUnion;
29448
29836
  exports.clearIndexedDbPersistence = clearIndexedDbPersistence;
@@ -29461,6 +29849,7 @@ exports.endAt = endAt;
29461
29849
  exports.endBefore = endBefore;
29462
29850
  exports.ensureFirestoreConfigured = ensureFirestoreConfigured;
29463
29851
  exports.executeWrite = executeWrite;
29852
+ exports.getCountFromServer = getCountFromServer;
29464
29853
  exports.getDoc = getDoc;
29465
29854
  exports.getDocFromCache = getDocFromCache;
29466
29855
  exports.getDocFromServer = getDocFromServer;