@firebase/firestore 3.4.7-canary.e9e5f6b3c → 3.4.8-canary.215e657ea

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 (90) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/firestore/src/core/query.d.ts +2 -4
  3. package/dist/firestore/src/core/target.d.ts +6 -4
  4. package/dist/firestore/src/local/index_manager.d.ts +24 -3
  5. package/dist/firestore/src/local/indexeddb_index_manager.d.ts +4 -7
  6. package/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  7. package/dist/firestore/src/local/indexeddb_schema.d.ts +1 -0
  8. package/dist/firestore/src/local/local_documents_view.d.ts +1 -1
  9. package/dist/firestore/src/local/memory_index_manager.d.ts +3 -2
  10. package/dist/firestore/src/local/query_engine.d.ts +44 -5
  11. package/dist/firestore/src/local/simple_db.d.ts +2 -0
  12. package/dist/firestore/src/model/collections.d.ts +1 -1
  13. package/dist/firestore/src/model/values.d.ts +14 -2
  14. package/dist/firestore/src/util/misc.d.ts +3 -0
  15. package/dist/firestore/test/unit/local/counting_query_engine.d.ts +2 -1
  16. package/dist/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  17. package/dist/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  18. package/dist/index.esm2017.js +4126 -4027
  19. package/dist/index.esm2017.js.map +1 -1
  20. package/dist/index.esm5.js +3957 -3865
  21. package/dist/index.esm5.js.map +1 -1
  22. package/dist/index.node.cjs.js +1698 -1562
  23. package/dist/index.node.cjs.js.map +1 -1
  24. package/dist/index.node.mjs +1698 -1562
  25. package/dist/index.node.mjs.map +1 -1
  26. package/dist/index.rn.js +4120 -4021
  27. package/dist/index.rn.js.map +1 -1
  28. package/dist/internal.d.ts +25 -3
  29. package/dist/lite/firestore/src/core/query.d.ts +2 -4
  30. package/dist/lite/firestore/src/core/target.d.ts +6 -4
  31. package/dist/lite/firestore/src/local/index_manager.d.ts +24 -3
  32. package/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts +4 -7
  33. package/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  34. package/dist/lite/firestore/src/local/indexeddb_schema.d.ts +1 -0
  35. package/dist/lite/firestore/src/local/local_documents_view.d.ts +1 -1
  36. package/dist/lite/firestore/src/local/memory_index_manager.d.ts +3 -2
  37. package/dist/lite/firestore/src/local/query_engine.d.ts +44 -5
  38. package/dist/lite/firestore/src/local/simple_db.d.ts +2 -0
  39. package/dist/lite/firestore/src/model/collections.d.ts +1 -1
  40. package/dist/lite/firestore/src/model/values.d.ts +14 -2
  41. package/dist/lite/firestore/src/util/misc.d.ts +3 -0
  42. package/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts +2 -1
  43. package/dist/lite/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  44. package/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  45. package/dist/lite/index.browser.esm2017.js +190 -184
  46. package/dist/lite/index.browser.esm2017.js.map +1 -1
  47. package/dist/lite/index.browser.esm5.js +209 -203
  48. package/dist/lite/index.browser.esm5.js.map +1 -1
  49. package/dist/lite/index.node.cjs.js +24 -10
  50. package/dist/lite/index.node.cjs.js.map +1 -1
  51. package/dist/lite/index.node.mjs +24 -10
  52. package/dist/lite/index.node.mjs.map +1 -1
  53. package/dist/lite/index.rn.esm2017.js +123 -117
  54. package/dist/lite/index.rn.esm2017.js.map +1 -1
  55. package/dist/lite/packages/firestore/dist/lite/index.browser.esm2017.d.ts +18 -18
  56. package/dist/lite/packages/firestore/src/core/query.d.ts +2 -4
  57. package/dist/lite/packages/firestore/src/core/target.d.ts +6 -4
  58. package/dist/lite/packages/firestore/src/local/index_manager.d.ts +24 -3
  59. package/dist/lite/packages/firestore/src/local/indexeddb_index_manager.d.ts +4 -7
  60. package/dist/lite/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  61. package/dist/lite/packages/firestore/src/local/indexeddb_schema.d.ts +1 -0
  62. package/dist/lite/packages/firestore/src/local/local_documents_view.d.ts +1 -1
  63. package/dist/lite/packages/firestore/src/local/memory_index_manager.d.ts +3 -2
  64. package/dist/lite/packages/firestore/src/local/query_engine.d.ts +44 -5
  65. package/dist/lite/packages/firestore/src/local/simple_db.d.ts +2 -0
  66. package/dist/lite/packages/firestore/src/model/collections.d.ts +1 -1
  67. package/dist/lite/packages/firestore/src/model/values.d.ts +14 -2
  68. package/dist/lite/packages/firestore/src/util/misc.d.ts +3 -0
  69. package/dist/lite/packages/firestore/test/unit/local/counting_query_engine.d.ts +2 -1
  70. package/dist/lite/packages/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  71. package/dist/lite/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  72. package/dist/packages/firestore/dist/index.esm2017.d.ts +168 -168
  73. package/dist/packages/firestore/src/core/query.d.ts +2 -4
  74. package/dist/packages/firestore/src/core/target.d.ts +6 -4
  75. package/dist/packages/firestore/src/local/index_manager.d.ts +24 -3
  76. package/dist/packages/firestore/src/local/indexeddb_index_manager.d.ts +4 -7
  77. package/dist/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  78. package/dist/packages/firestore/src/local/indexeddb_schema.d.ts +1 -0
  79. package/dist/packages/firestore/src/local/local_documents_view.d.ts +1 -1
  80. package/dist/packages/firestore/src/local/memory_index_manager.d.ts +3 -2
  81. package/dist/packages/firestore/src/local/query_engine.d.ts +44 -5
  82. package/dist/packages/firestore/src/local/simple_db.d.ts +2 -0
  83. package/dist/packages/firestore/src/model/collections.d.ts +1 -1
  84. package/dist/packages/firestore/src/model/values.d.ts +14 -2
  85. package/dist/packages/firestore/src/util/misc.d.ts +3 -0
  86. package/dist/packages/firestore/test/unit/local/counting_query_engine.d.ts +2 -1
  87. package/dist/packages/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  88. package/dist/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  89. package/dist/private.d.ts +25 -3
  90. 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.4.7-canary.e9e5f6b3c";
36
+ const version$1 = "3.4.8-canary.215e657ea";
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.6.10-canary.e9e5f6b3c";
89
+ const version = "9.6.11-canary.215e657ea";
90
90
 
91
91
  /**
92
92
  * @license
@@ -2311,9 +2311,7 @@ class SimpleDbStore {
2311
2311
  cursor.continue(controller.skipToKey);
2312
2312
  }
2313
2313
  };
2314
- }).next(() => {
2315
- return PersistencePromise.waitFor(results);
2316
- });
2314
+ }).next(() => PersistencePromise.waitFor(results));
2317
2315
  }
2318
2316
  options(indexOrRange, range) {
2319
2317
  let indexName = undefined;
@@ -3348,7 +3346,7 @@ function typeOrder(value) {
3348
3346
  return 4 /* ServerTimestampValue */;
3349
3347
  }
3350
3348
  else if (isMaxValue(value)) {
3351
- return 9 /* ArrayValue */;
3349
+ return 9007199254740991 /* MaxValue */;
3352
3350
  }
3353
3351
  return 10 /* ObjectValue */;
3354
3352
  }
@@ -3560,6 +3558,15 @@ function compareArrays(left, right) {
3560
3558
  return primitiveComparator(leftArray.length, rightArray.length);
3561
3559
  }
3562
3560
  function compareMaps(left, right) {
3561
+ if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {
3562
+ return 0;
3563
+ }
3564
+ else if (left === MAX_VALUE.mapValue) {
3565
+ return 1;
3566
+ }
3567
+ else if (right === MAX_VALUE.mapValue) {
3568
+ return -1;
3569
+ }
3563
3570
  const leftMap = left.fields || {};
3564
3571
  const leftKeys = Object.keys(leftMap);
3565
3572
  const rightMap = right.fields || {};
@@ -3807,27 +3814,31 @@ function valuesGetUpperBound(value) {
3807
3814
  return fail();
3808
3815
  }
3809
3816
  }
3810
- function valuesMax(left, right) {
3811
- if (left === undefined) {
3812
- return right;
3817
+ function lowerBoundCompare(left, right) {
3818
+ const cmp = valueCompare(left.value, right.value);
3819
+ if (cmp !== 0) {
3820
+ return cmp;
3813
3821
  }
3814
- else if (right === undefined) {
3815
- return left;
3822
+ if (left.inclusive && !right.inclusive) {
3823
+ return -1;
3816
3824
  }
3817
- else {
3818
- return valueCompare(left, right) > 0 ? left : right;
3825
+ else if (!left.inclusive && right.inclusive) {
3826
+ return 1;
3819
3827
  }
3828
+ return 0;
3820
3829
  }
3821
- function valuesMin(left, right) {
3822
- if (left === undefined) {
3823
- return right;
3830
+ function upperBoundCompare(left, right) {
3831
+ const cmp = valueCompare(left.value, right.value);
3832
+ if (cmp !== 0) {
3833
+ return cmp;
3824
3834
  }
3825
- else if (right === undefined) {
3826
- return left;
3835
+ if (left.inclusive && !right.inclusive) {
3836
+ return 1;
3827
3837
  }
3828
- else {
3829
- return valueCompare(left, right) < 0 ? left : right;
3838
+ else if (!left.inclusive && right.inclusive) {
3839
+ return -1;
3830
3840
  }
3841
+ return 0;
3831
3842
  }
3832
3843
 
3833
3844
  /**
@@ -4337,7 +4348,7 @@ function indexOffsetComparator(left, right) {
4337
4348
 
4338
4349
  /**
4339
4350
  * @license
4340
- * Copyright 2019 Google LLC
4351
+ * Copyright 2017 Google LLC
4341
4352
  *
4342
4353
  * Licensed under the Apache License, Version 2.0 (the "License");
4343
4354
  * you may not use this file except in compliance with the License.
@@ -4351,609 +4362,445 @@ function indexOffsetComparator(left, right) {
4351
4362
  * See the License for the specific language governing permissions and
4352
4363
  * limitations under the License.
4353
4364
  */
4354
- // Visible for testing
4355
- class TargetImpl {
4356
- constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4357
- this.path = path;
4358
- this.collectionGroup = collectionGroup;
4359
- this.orderBy = orderBy;
4360
- this.filters = filters;
4361
- this.limit = limit;
4362
- this.startAt = startAt;
4363
- this.endAt = endAt;
4364
- this.memoizedCanonicalId = null;
4365
+ // An immutable sorted map implementation, based on a Left-leaning Red-Black
4366
+ // tree.
4367
+ class SortedMap {
4368
+ constructor(comparator, root) {
4369
+ this.comparator = comparator;
4370
+ this.root = root ? root : LLRBNode.EMPTY;
4365
4371
  }
4366
- }
4367
- /**
4368
- * Initializes a Target with a path and optional additional query constraints.
4369
- * Path must currently be empty if this is a collection group query.
4370
- *
4371
- * NOTE: you should always construct `Target` from `Query.toTarget` instead of
4372
- * using this factory method, because `Query` provides an implicit `orderBy`
4373
- * property.
4374
- */
4375
- function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4376
- return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
4377
- }
4378
- function canonifyTarget(target) {
4379
- const targetImpl = debugCast(target);
4380
- if (targetImpl.memoizedCanonicalId === null) {
4381
- let str = targetImpl.path.canonicalString();
4382
- if (targetImpl.collectionGroup !== null) {
4383
- str += '|cg:' + targetImpl.collectionGroup;
4384
- }
4385
- str += '|f:';
4386
- str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
4387
- str += '|ob:';
4388
- str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
4389
- if (!isNullOrUndefined(targetImpl.limit)) {
4390
- str += '|l:';
4391
- str += targetImpl.limit;
4392
- }
4393
- if (targetImpl.startAt) {
4394
- str += '|lb:';
4395
- str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
4396
- str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
4397
- }
4398
- if (targetImpl.endAt) {
4399
- str += '|ub:';
4400
- str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
4401
- str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
4402
- }
4403
- targetImpl.memoizedCanonicalId = str;
4372
+ // Returns a copy of the map, with the specified key/value added or replaced.
4373
+ insert(key, value) {
4374
+ return new SortedMap(this.comparator, this.root
4375
+ .insert(key, value, this.comparator)
4376
+ .copy(null, null, LLRBNode.BLACK, null, null));
4404
4377
  }
4405
- return targetImpl.memoizedCanonicalId;
4406
- }
4407
- function stringifyTarget(target) {
4408
- let str = target.path.canonicalString();
4409
- if (target.collectionGroup !== null) {
4410
- str += ' collectionGroup=' + target.collectionGroup;
4378
+ // Returns a copy of the map, with the specified key removed.
4379
+ remove(key) {
4380
+ return new SortedMap(this.comparator, this.root
4381
+ .remove(key, this.comparator)
4382
+ .copy(null, null, LLRBNode.BLACK, null, null));
4411
4383
  }
4412
- if (target.filters.length > 0) {
4413
- str += `, filters: [${target.filters
4414
- .map(f => stringifyFilter(f))
4415
- .join(', ')}]`;
4384
+ // Returns the value of the node with the given key, or null.
4385
+ get(key) {
4386
+ let node = this.root;
4387
+ while (!node.isEmpty()) {
4388
+ const cmp = this.comparator(key, node.key);
4389
+ if (cmp === 0) {
4390
+ return node.value;
4391
+ }
4392
+ else if (cmp < 0) {
4393
+ node = node.left;
4394
+ }
4395
+ else if (cmp > 0) {
4396
+ node = node.right;
4397
+ }
4398
+ }
4399
+ return null;
4416
4400
  }
4417
- if (!isNullOrUndefined(target.limit)) {
4418
- str += ', limit: ' + target.limit;
4401
+ // Returns the index of the element in this sorted map, or -1 if it doesn't
4402
+ // exist.
4403
+ indexOf(key) {
4404
+ // Number of nodes that were pruned when descending right
4405
+ let prunedNodes = 0;
4406
+ let node = this.root;
4407
+ while (!node.isEmpty()) {
4408
+ const cmp = this.comparator(key, node.key);
4409
+ if (cmp === 0) {
4410
+ return prunedNodes + node.left.size;
4411
+ }
4412
+ else if (cmp < 0) {
4413
+ node = node.left;
4414
+ }
4415
+ else {
4416
+ // Count all nodes left of the node plus the node itself
4417
+ prunedNodes += node.left.size + 1;
4418
+ node = node.right;
4419
+ }
4420
+ }
4421
+ // Node not found
4422
+ return -1;
4419
4423
  }
4420
- if (target.orderBy.length > 0) {
4421
- str += `, orderBy: [${target.orderBy
4422
- .map(o => stringifyOrderBy(o))
4423
- .join(', ')}]`;
4424
+ isEmpty() {
4425
+ return this.root.isEmpty();
4424
4426
  }
4425
- if (target.startAt) {
4426
- str += ', startAt: ';
4427
- str += target.startAt.inclusive ? 'b:' : 'a:';
4428
- str += target.startAt.position.map(p => canonicalId(p)).join(',');
4427
+ // Returns the total number of nodes in the map.
4428
+ get size() {
4429
+ return this.root.size;
4429
4430
  }
4430
- if (target.endAt) {
4431
- str += ', endAt: ';
4432
- str += target.endAt.inclusive ? 'a:' : 'b:';
4433
- str += target.endAt.position.map(p => canonicalId(p)).join(',');
4431
+ // Returns the minimum key in the map.
4432
+ minKey() {
4433
+ return this.root.minKey();
4434
4434
  }
4435
- return `Target(${str})`;
4436
- }
4437
- function targetEquals(left, right) {
4438
- if (left.limit !== right.limit) {
4439
- return false;
4435
+ // Returns the maximum key in the map.
4436
+ maxKey() {
4437
+ return this.root.maxKey();
4440
4438
  }
4441
- if (left.orderBy.length !== right.orderBy.length) {
4442
- return false;
4439
+ // Traverses the map in key order and calls the specified action function
4440
+ // for each key/value pair. If action returns true, traversal is aborted.
4441
+ // Returns the first truthy value returned by action, or the last falsey
4442
+ // value returned by action.
4443
+ inorderTraversal(action) {
4444
+ return this.root.inorderTraversal(action);
4443
4445
  }
4444
- for (let i = 0; i < left.orderBy.length; i++) {
4445
- if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
4446
+ forEach(fn) {
4447
+ this.inorderTraversal((k, v) => {
4448
+ fn(k, v);
4446
4449
  return false;
4447
- }
4448
- }
4449
- if (left.filters.length !== right.filters.length) {
4450
- return false;
4450
+ });
4451
4451
  }
4452
- for (let i = 0; i < left.filters.length; i++) {
4453
- if (!filterEquals(left.filters[i], right.filters[i])) {
4452
+ toString() {
4453
+ const descriptions = [];
4454
+ this.inorderTraversal((k, v) => {
4455
+ descriptions.push(`${k}:${v}`);
4454
4456
  return false;
4455
- }
4457
+ });
4458
+ return `{${descriptions.join(', ')}}`;
4456
4459
  }
4457
- if (left.collectionGroup !== right.collectionGroup) {
4458
- return false;
4460
+ // Traverses the map in reverse key order and calls the specified action
4461
+ // function for each key/value pair. If action returns true, traversal is
4462
+ // aborted.
4463
+ // Returns the first truthy value returned by action, or the last falsey
4464
+ // value returned by action.
4465
+ reverseTraversal(action) {
4466
+ return this.root.reverseTraversal(action);
4459
4467
  }
4460
- if (!left.path.isEqual(right.path)) {
4461
- return false;
4468
+ // Returns an iterator over the SortedMap.
4469
+ getIterator() {
4470
+ return new SortedMapIterator(this.root, null, this.comparator, false);
4462
4471
  }
4463
- if (!boundEquals(left.startAt, right.startAt)) {
4464
- return false;
4472
+ getIteratorFrom(key) {
4473
+ return new SortedMapIterator(this.root, key, this.comparator, false);
4465
4474
  }
4466
- return boundEquals(left.endAt, right.endAt);
4467
- }
4468
- function targetIsDocumentTarget(target) {
4469
- return (DocumentKey.isDocumentKey(target.path) &&
4470
- target.collectionGroup === null &&
4471
- target.filters.length === 0);
4472
- }
4473
- /** Returns the field filters that target the given field path. */
4474
- function targetGetFieldFiltersForPath(target, path) {
4475
- return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
4476
- }
4477
- /**
4478
- * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
4479
- * filters. Returns `null` if there are no such filters.
4480
- */
4481
- function targetGetArrayValues(target, fieldIndex) {
4482
- const segment = fieldIndexGetArraySegment(fieldIndex);
4483
- if (segment === undefined) {
4484
- return null;
4475
+ getReverseIterator() {
4476
+ return new SortedMapIterator(this.root, null, this.comparator, true);
4485
4477
  }
4486
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4487
- switch (fieldFilter.op) {
4488
- case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
4489
- return fieldFilter.value.arrayValue.values || [];
4490
- case "array-contains" /* ARRAY_CONTAINS */:
4491
- return [fieldFilter.value];
4492
- // Remaining filters are not array filters.
4493
- }
4478
+ getReverseIteratorFrom(key) {
4479
+ return new SortedMapIterator(this.root, key, this.comparator, true);
4494
4480
  }
4495
- return null;
4496
- }
4497
- /**
4498
- * Returns the list of values that are used in != or NOT_IN filters. Returns
4499
- * `null` if there are no such filters.
4500
- */
4501
- function targetGetNotInValues(target, fieldIndex) {
4502
- const values = new Map();
4503
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4504
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4505
- switch (fieldFilter.op) {
4506
- case "==" /* EQUAL */:
4507
- case "in" /* IN */:
4508
- // Encode equality prefix, which is encoded in the index value before
4509
- // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
4510
- // `value != 'ab'`).
4511
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4512
- break;
4513
- case "not-in" /* NOT_IN */:
4514
- case "!=" /* NOT_EQUAL */:
4515
- // NotIn/NotEqual is always a suffix. There cannot be any remaining
4516
- // segments and hence we can return early here.
4517
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4518
- return Array.from(values.values());
4519
- // Remaining filters cannot be used as notIn bounds.
4481
+ } // end SortedMap
4482
+ // An iterator over an LLRBNode.
4483
+ class SortedMapIterator {
4484
+ constructor(node, startKey, comparator, isReverse) {
4485
+ this.isReverse = isReverse;
4486
+ this.nodeStack = [];
4487
+ let cmp = 1;
4488
+ while (!node.isEmpty()) {
4489
+ cmp = startKey ? comparator(node.key, startKey) : 1;
4490
+ // flip the comparison if we're going in reverse
4491
+ if (startKey && isReverse) {
4492
+ cmp *= -1;
4493
+ }
4494
+ if (cmp < 0) {
4495
+ // This node is less than our start key. ignore it
4496
+ if (this.isReverse) {
4497
+ node = node.left;
4498
+ }
4499
+ else {
4500
+ node = node.right;
4501
+ }
4502
+ }
4503
+ else if (cmp === 0) {
4504
+ // This node is exactly equal to our start key. Push it on the stack,
4505
+ // but stop iterating;
4506
+ this.nodeStack.push(node);
4507
+ break;
4508
+ }
4509
+ else {
4510
+ // This node is greater than our start key, add it to the stack and move
4511
+ // to the next one
4512
+ this.nodeStack.push(node);
4513
+ if (this.isReverse) {
4514
+ node = node.right;
4515
+ }
4516
+ else {
4517
+ node = node.left;
4518
+ }
4520
4519
  }
4521
4520
  }
4522
4521
  }
4523
- return null;
4524
- }
4525
- /**
4526
- * Returns a lower bound of field values that can be used as a starting point to
4527
- * scan the index defined by `fieldIndex`. Returns `null` if no lower bound
4528
- * exists.
4529
- */
4530
- function targetGetLowerBound(target, fieldIndex) {
4531
- const values = [];
4532
- let inclusive = true;
4533
- // For each segment, retrieve a lower bound if there is a suitable filter or
4534
- // startAt.
4535
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4536
- const segmentBound = segment.kind === 0 /* ASCENDING */
4537
- ? targetGetLowerBoundForField(target, segment.fieldPath, target.startAt)
4538
- : targetGetUpperBoundForField(target, segment.fieldPath, target.startAt);
4539
- if (!segmentBound.value) {
4540
- // No lower bound exists
4541
- return null;
4522
+ getNext() {
4523
+ let node = this.nodeStack.pop();
4524
+ const result = { key: node.key, value: node.value };
4525
+ if (this.isReverse) {
4526
+ node = node.left;
4527
+ while (!node.isEmpty()) {
4528
+ this.nodeStack.push(node);
4529
+ node = node.right;
4530
+ }
4542
4531
  }
4543
- values.push(segmentBound.value);
4544
- inclusive && (inclusive = segmentBound.inclusive);
4532
+ else {
4533
+ node = node.right;
4534
+ while (!node.isEmpty()) {
4535
+ this.nodeStack.push(node);
4536
+ node = node.left;
4537
+ }
4538
+ }
4539
+ return result;
4545
4540
  }
4546
- return new Bound(values, inclusive);
4547
- }
4548
- /**
4549
- * Returns an upper bound of field values that can be used as an ending point
4550
- * when scanning the index defined by `fieldIndex`. Returns `null` if no
4551
- * upper bound exists.
4552
- */
4553
- function targetGetUpperBound(target, fieldIndex) {
4554
- const values = [];
4555
- let inclusive = true;
4556
- // For each segment, retrieve an upper bound if there is a suitable filter or
4557
- // endAt.
4558
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4559
- const segmentBound = segment.kind === 0 /* ASCENDING */
4560
- ? targetGetUpperBoundForField(target, segment.fieldPath, target.endAt)
4561
- : targetGetLowerBoundForField(target, segment.fieldPath, target.endAt);
4562
- if (!segmentBound.value) {
4563
- // No upper bound exists
4541
+ hasNext() {
4542
+ return this.nodeStack.length > 0;
4543
+ }
4544
+ peek() {
4545
+ if (this.nodeStack.length === 0) {
4564
4546
  return null;
4565
4547
  }
4566
- values.push(segmentBound.value);
4567
- inclusive && (inclusive = segmentBound.inclusive);
4548
+ const node = this.nodeStack[this.nodeStack.length - 1];
4549
+ return { key: node.key, value: node.value };
4568
4550
  }
4569
- return new Bound(values, inclusive);
4570
- }
4571
- /**
4572
- * Returns the value to use as the lower bound for ascending index segment at
4573
- * the provided `fieldPath` (or the upper bound for an descending segment).
4574
- */
4575
- function targetGetLowerBoundForField(target, fieldPath, bound) {
4576
- let value = undefined;
4577
- let inclusive = true;
4578
- // Process all filters to find a value for the current field segment
4579
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4580
- let filterValue = undefined;
4581
- let filterInclusive = true;
4582
- switch (fieldFilter.op) {
4583
- case "<" /* LESS_THAN */:
4584
- case "<=" /* LESS_THAN_OR_EQUAL */:
4585
- filterValue = valuesGetLowerBound(fieldFilter.value);
4586
- break;
4587
- case "==" /* EQUAL */:
4588
- case "in" /* IN */:
4589
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4590
- filterValue = fieldFilter.value;
4591
- break;
4592
- case ">" /* GREATER_THAN */:
4593
- filterValue = fieldFilter.value;
4594
- filterInclusive = false;
4595
- break;
4596
- case "!=" /* NOT_EQUAL */:
4597
- case "not-in" /* NOT_IN */:
4598
- filterValue = MIN_VALUE;
4599
- break;
4600
- // Remaining filters cannot be used as lower bounds.
4551
+ } // end SortedMapIterator
4552
+ // Represents a node in a Left-leaning Red-Black tree.
4553
+ class LLRBNode {
4554
+ constructor(key, value, color, left, right) {
4555
+ this.key = key;
4556
+ this.value = value;
4557
+ this.color = color != null ? color : LLRBNode.RED;
4558
+ this.left = left != null ? left : LLRBNode.EMPTY;
4559
+ this.right = right != null ? right : LLRBNode.EMPTY;
4560
+ this.size = this.left.size + 1 + this.right.size;
4561
+ }
4562
+ // Returns a copy of the current node, optionally replacing pieces of it.
4563
+ copy(key, value, color, left, right) {
4564
+ return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
4565
+ }
4566
+ isEmpty() {
4567
+ return false;
4568
+ }
4569
+ // Traverses the tree in key order and calls the specified action function
4570
+ // for each node. If action returns true, traversal is aborted.
4571
+ // Returns the first truthy value returned by action, or the last falsey
4572
+ // value returned by action.
4573
+ inorderTraversal(action) {
4574
+ return (this.left.inorderTraversal(action) ||
4575
+ action(this.key, this.value) ||
4576
+ this.right.inorderTraversal(action));
4577
+ }
4578
+ // Traverses the tree in reverse key order and calls the specified action
4579
+ // function for each node. If action returns true, traversal is aborted.
4580
+ // Returns the first truthy value returned by action, or the last falsey
4581
+ // value returned by action.
4582
+ reverseTraversal(action) {
4583
+ return (this.right.reverseTraversal(action) ||
4584
+ action(this.key, this.value) ||
4585
+ this.left.reverseTraversal(action));
4586
+ }
4587
+ // Returns the minimum node in the tree.
4588
+ min() {
4589
+ if (this.left.isEmpty()) {
4590
+ return this;
4601
4591
  }
4602
- if (valuesMax(value, filterValue) === filterValue) {
4603
- value = filterValue;
4604
- inclusive = filterInclusive;
4592
+ else {
4593
+ return this.left.min();
4605
4594
  }
4606
4595
  }
4607
- // If there is an additional bound, compare the values against the existing
4608
- // range to see if we can narrow the scope.
4609
- if (bound !== null) {
4610
- for (let i = 0; i < target.orderBy.length; ++i) {
4611
- const orderBy = target.orderBy[i];
4612
- if (orderBy.field.isEqual(fieldPath)) {
4613
- const cursorValue = bound.position[i];
4614
- if (valuesMax(value, cursorValue) === cursorValue) {
4615
- value = cursorValue;
4616
- inclusive = bound.inclusive;
4617
- }
4618
- break;
4619
- }
4620
- }
4596
+ // Returns the maximum key in the tree.
4597
+ minKey() {
4598
+ return this.min().key;
4621
4599
  }
4622
- return { value, inclusive };
4623
- }
4624
- /**
4625
- * Returns the value to use as the upper bound for ascending index segment at
4626
- * the provided `fieldPath` (or the lower bound for an descending segment).
4627
- */
4628
- function targetGetUpperBoundForField(target, fieldPath, bound) {
4629
- let value = undefined;
4630
- let inclusive = true;
4631
- // Process all filters to find a value for the current field segment
4632
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4633
- let filterValue = undefined;
4634
- let filterInclusive = true;
4635
- switch (fieldFilter.op) {
4636
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4637
- case ">" /* GREATER_THAN */:
4638
- filterValue = valuesGetUpperBound(fieldFilter.value);
4639
- filterInclusive = false;
4640
- break;
4641
- case "==" /* EQUAL */:
4642
- case "in" /* IN */:
4643
- case "<=" /* LESS_THAN_OR_EQUAL */:
4644
- filterValue = fieldFilter.value;
4645
- break;
4646
- case "<" /* LESS_THAN */:
4647
- filterValue = fieldFilter.value;
4648
- filterInclusive = false;
4649
- break;
4650
- case "!=" /* NOT_EQUAL */:
4651
- case "not-in" /* NOT_IN */:
4652
- filterValue = MAX_VALUE;
4653
- break;
4654
- // Remaining filters cannot be used as upper bounds.
4600
+ // Returns the maximum key in the tree.
4601
+ maxKey() {
4602
+ if (this.right.isEmpty()) {
4603
+ return this.key;
4655
4604
  }
4656
- if (valuesMin(value, filterValue) === filterValue) {
4657
- value = filterValue;
4658
- inclusive = filterInclusive;
4605
+ else {
4606
+ return this.right.maxKey();
4659
4607
  }
4660
4608
  }
4661
- // If there is an additional bound, compare the values against the existing
4662
- // range to see if we can narrow the scope.
4663
- if (bound !== null) {
4664
- for (let i = 0; i < target.orderBy.length; ++i) {
4665
- const orderBy = target.orderBy[i];
4666
- if (orderBy.field.isEqual(fieldPath)) {
4667
- const cursorValue = bound.position[i];
4668
- if (valuesMin(value, cursorValue) === cursorValue) {
4669
- value = cursorValue;
4670
- inclusive = bound.inclusive;
4671
- }
4672
- break;
4673
- }
4609
+ // Returns new tree, with the key/value added.
4610
+ insert(key, value, comparator) {
4611
+ let n = this;
4612
+ const cmp = comparator(key, n.key);
4613
+ if (cmp < 0) {
4614
+ n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
4615
+ }
4616
+ else if (cmp === 0) {
4617
+ n = n.copy(null, value, null, null, null);
4618
+ }
4619
+ else {
4620
+ n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
4674
4621
  }
4622
+ return n.fixUp();
4675
4623
  }
4676
- return { value, inclusive };
4677
- }
4678
- class Filter {
4679
- }
4680
- class FieldFilter extends Filter {
4681
- constructor(field, op, value) {
4682
- super();
4683
- this.field = field;
4684
- this.op = op;
4685
- this.value = value;
4624
+ removeMin() {
4625
+ if (this.left.isEmpty()) {
4626
+ return LLRBNode.EMPTY;
4627
+ }
4628
+ let n = this;
4629
+ if (!n.left.isRed() && !n.left.left.isRed()) {
4630
+ n = n.moveRedLeft();
4631
+ }
4632
+ n = n.copy(null, null, null, n.left.removeMin(), null);
4633
+ return n.fixUp();
4686
4634
  }
4687
- /**
4688
- * Creates a filter based on the provided arguments.
4689
- */
4690
- static create(field, op, value) {
4691
- if (field.isKeyField()) {
4692
- if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
4693
- return this.createKeyFieldInFilter(field, op, value);
4635
+ // Returns new tree, with the specified item removed.
4636
+ remove(key, comparator) {
4637
+ let smallest;
4638
+ let n = this;
4639
+ if (comparator(key, n.key) < 0) {
4640
+ if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
4641
+ n = n.moveRedLeft();
4694
4642
  }
4695
- else {
4696
- return new KeyFieldFilter(field, op, value);
4643
+ n = n.copy(null, null, null, n.left.remove(key, comparator), null);
4644
+ }
4645
+ else {
4646
+ if (n.left.isRed()) {
4647
+ n = n.rotateRight();
4648
+ }
4649
+ if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
4650
+ n = n.moveRedRight();
4651
+ }
4652
+ if (comparator(key, n.key) === 0) {
4653
+ if (n.right.isEmpty()) {
4654
+ return LLRBNode.EMPTY;
4655
+ }
4656
+ else {
4657
+ smallest = n.right.min();
4658
+ n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
4659
+ }
4697
4660
  }
4661
+ n = n.copy(null, null, null, null, n.right.remove(key, comparator));
4698
4662
  }
4699
- else if (op === "array-contains" /* ARRAY_CONTAINS */) {
4700
- return new ArrayContainsFilter(field, value);
4663
+ return n.fixUp();
4664
+ }
4665
+ isRed() {
4666
+ return this.color;
4667
+ }
4668
+ // Returns new tree after performing any needed rotations.
4669
+ fixUp() {
4670
+ let n = this;
4671
+ if (n.right.isRed() && !n.left.isRed()) {
4672
+ n = n.rotateLeft();
4701
4673
  }
4702
- else if (op === "in" /* IN */) {
4703
- return new InFilter(field, value);
4674
+ if (n.left.isRed() && n.left.left.isRed()) {
4675
+ n = n.rotateRight();
4704
4676
  }
4705
- else if (op === "not-in" /* NOT_IN */) {
4706
- return new NotInFilter(field, value);
4677
+ if (n.left.isRed() && n.right.isRed()) {
4678
+ n = n.colorFlip();
4707
4679
  }
4708
- else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
4709
- return new ArrayContainsAnyFilter(field, value);
4680
+ return n;
4681
+ }
4682
+ moveRedLeft() {
4683
+ let n = this.colorFlip();
4684
+ if (n.right.left.isRed()) {
4685
+ n = n.copy(null, null, null, null, n.right.rotateRight());
4686
+ n = n.rotateLeft();
4687
+ n = n.colorFlip();
4710
4688
  }
4711
- else {
4712
- return new FieldFilter(field, op, value);
4689
+ return n;
4690
+ }
4691
+ moveRedRight() {
4692
+ let n = this.colorFlip();
4693
+ if (n.left.left.isRed()) {
4694
+ n = n.rotateRight();
4695
+ n = n.colorFlip();
4713
4696
  }
4697
+ return n;
4714
4698
  }
4715
- static createKeyFieldInFilter(field, op, value) {
4716
- return op === "in" /* IN */
4717
- ? new KeyFieldInFilter(field, value)
4718
- : new KeyFieldNotInFilter(field, value);
4699
+ rotateLeft() {
4700
+ const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
4701
+ return this.right.copy(null, null, this.color, nl, null);
4719
4702
  }
4720
- matches(doc) {
4721
- const other = doc.data.field(this.field);
4722
- // Types do not have to match in NOT_EQUAL filters.
4723
- if (this.op === "!=" /* NOT_EQUAL */) {
4724
- return (other !== null &&
4725
- this.matchesComparison(valueCompare(other, this.value)));
4703
+ rotateRight() {
4704
+ const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
4705
+ return this.left.copy(null, null, this.color, null, nr);
4706
+ }
4707
+ colorFlip() {
4708
+ const left = this.left.copy(null, null, !this.left.color, null, null);
4709
+ const right = this.right.copy(null, null, !this.right.color, null, null);
4710
+ return this.copy(null, null, !this.color, left, right);
4711
+ }
4712
+ // For testing.
4713
+ checkMaxDepth() {
4714
+ const blackDepth = this.check();
4715
+ if (Math.pow(2.0, blackDepth) <= this.size + 1) {
4716
+ return true;
4717
+ }
4718
+ else {
4719
+ return false;
4726
4720
  }
4727
- // Only compare types with matching backend order (such as double and int).
4728
- return (other !== null &&
4729
- typeOrder(this.value) === typeOrder(other) &&
4730
- this.matchesComparison(valueCompare(other, this.value)));
4731
4721
  }
4732
- matchesComparison(comparison) {
4733
- switch (this.op) {
4734
- case "<" /* LESS_THAN */:
4735
- return comparison < 0;
4736
- case "<=" /* LESS_THAN_OR_EQUAL */:
4737
- return comparison <= 0;
4738
- case "==" /* EQUAL */:
4739
- return comparison === 0;
4740
- case "!=" /* NOT_EQUAL */:
4741
- return comparison !== 0;
4742
- case ">" /* GREATER_THAN */:
4743
- return comparison > 0;
4744
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4745
- return comparison >= 0;
4746
- default:
4747
- return fail();
4722
+ // In a balanced RB tree, the black-depth (number of black nodes) from root to
4723
+ // leaves is equal on both sides. This function verifies that or asserts.
4724
+ check() {
4725
+ if (this.isRed() && this.left.isRed()) {
4726
+ throw fail();
4727
+ }
4728
+ if (this.right.isRed()) {
4729
+ throw fail();
4730
+ }
4731
+ const blackDepth = this.left.check();
4732
+ if (blackDepth !== this.right.check()) {
4733
+ throw fail();
4734
+ }
4735
+ else {
4736
+ return blackDepth + (this.isRed() ? 0 : 1);
4748
4737
  }
4749
4738
  }
4750
- isInequality() {
4751
- return ([
4752
- "<" /* LESS_THAN */,
4753
- "<=" /* LESS_THAN_OR_EQUAL */,
4754
- ">" /* GREATER_THAN */,
4755
- ">=" /* GREATER_THAN_OR_EQUAL */,
4756
- "!=" /* NOT_EQUAL */,
4757
- "not-in" /* NOT_IN */
4758
- ].indexOf(this.op) >= 0);
4739
+ } // end LLRBNode
4740
+ // Empty node is shared between all LLRB trees.
4741
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4742
+ LLRBNode.EMPTY = null;
4743
+ LLRBNode.RED = true;
4744
+ LLRBNode.BLACK = false;
4745
+ // Represents an empty node (a leaf node in the Red-Black Tree).
4746
+ class LLRBEmptyNode {
4747
+ constructor() {
4748
+ this.size = 0;
4759
4749
  }
4760
- }
4761
- function canonifyFilter(filter) {
4762
- // TODO(b/29183165): Technically, this won't be unique if two values have
4763
- // the same description, such as the int 3 and the string "3". So we should
4764
- // add the types in here somehow, too.
4765
- return (filter.field.canonicalString() +
4766
- filter.op.toString() +
4767
- canonicalId(filter.value));
4768
- }
4769
- function filterEquals(f1, f2) {
4770
- return (f1.op === f2.op &&
4771
- f1.field.isEqual(f2.field) &&
4772
- valueEquals(f1.value, f2.value));
4773
- }
4774
- /** Returns a debug description for `filter`. */
4775
- function stringifyFilter(filter) {
4776
- return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
4777
- }
4778
- /** Filter that matches on key fields (i.e. '__name__'). */
4779
- class KeyFieldFilter extends FieldFilter {
4780
- constructor(field, op, value) {
4781
- super(field, op, value);
4782
- this.key = DocumentKey.fromName(value.referenceValue);
4750
+ get key() {
4751
+ throw fail();
4783
4752
  }
4784
- matches(doc) {
4785
- const comparison = DocumentKey.comparator(doc.key, this.key);
4786
- return this.matchesComparison(comparison);
4753
+ get value() {
4754
+ throw fail();
4787
4755
  }
4788
- }
4789
- /** Filter that matches on key fields within an array. */
4790
- class KeyFieldInFilter extends FieldFilter {
4791
- constructor(field, value) {
4792
- super(field, "in" /* IN */, value);
4793
- this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
4756
+ get color() {
4757
+ throw fail();
4794
4758
  }
4795
- matches(doc) {
4796
- return this.keys.some(key => key.isEqual(doc.key));
4759
+ get left() {
4760
+ throw fail();
4797
4761
  }
4798
- }
4799
- /** Filter that matches on key fields not present within an array. */
4800
- class KeyFieldNotInFilter extends FieldFilter {
4801
- constructor(field, value) {
4802
- super(field, "not-in" /* NOT_IN */, value);
4803
- this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
4762
+ get right() {
4763
+ throw fail();
4804
4764
  }
4805
- matches(doc) {
4806
- return !this.keys.some(key => key.isEqual(doc.key));
4765
+ // Returns a copy of the current node.
4766
+ copy(key, value, color, left, right) {
4767
+ return this;
4807
4768
  }
4808
- }
4809
- function extractDocumentKeysFromArrayValue(op, value) {
4810
- var _a;
4811
- return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
4812
- return DocumentKey.fromName(v.referenceValue);
4813
- });
4814
- }
4815
- /** A Filter that implements the array-contains operator. */
4816
- class ArrayContainsFilter extends FieldFilter {
4817
- constructor(field, value) {
4818
- super(field, "array-contains" /* ARRAY_CONTAINS */, value);
4769
+ // Returns a copy of the tree, with the specified key/value added.
4770
+ insert(key, value, comparator) {
4771
+ return new LLRBNode(key, value);
4819
4772
  }
4820
- matches(doc) {
4821
- const other = doc.data.field(this.field);
4822
- return isArray(other) && arrayValueContains(other.arrayValue, this.value);
4773
+ // Returns a copy of the tree, with the specified key removed.
4774
+ remove(key, comparator) {
4775
+ return this;
4823
4776
  }
4824
- }
4825
- /** A Filter that implements the IN operator. */
4826
- class InFilter extends FieldFilter {
4827
- constructor(field, value) {
4828
- super(field, "in" /* IN */, value);
4829
- }
4830
- matches(doc) {
4831
- const other = doc.data.field(this.field);
4832
- return other !== null && arrayValueContains(this.value.arrayValue, other);
4833
- }
4834
- }
4835
- /** A Filter that implements the not-in operator. */
4836
- class NotInFilter extends FieldFilter {
4837
- constructor(field, value) {
4838
- super(field, "not-in" /* NOT_IN */, value);
4839
- }
4840
- matches(doc) {
4841
- if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
4842
- return false;
4843
- }
4844
- const other = doc.data.field(this.field);
4845
- return other !== null && !arrayValueContains(this.value.arrayValue, other);
4846
- }
4847
- }
4848
- /** A Filter that implements the array-contains-any operator. */
4849
- class ArrayContainsAnyFilter extends FieldFilter {
4850
- constructor(field, value) {
4851
- super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
4852
- }
4853
- matches(doc) {
4854
- const other = doc.data.field(this.field);
4855
- if (!isArray(other) || !other.arrayValue.values) {
4856
- return false;
4857
- }
4858
- return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
4777
+ isEmpty() {
4778
+ return true;
4859
4779
  }
4860
- }
4861
- /**
4862
- * Represents a bound of a query.
4863
- *
4864
- * The bound is specified with the given components representing a position and
4865
- * whether it's just before or just after the position (relative to whatever the
4866
- * query order is).
4867
- *
4868
- * The position represents a logical index position for a query. It's a prefix
4869
- * of values for the (potentially implicit) order by clauses of a query.
4870
- *
4871
- * Bound provides a function to determine whether a document comes before or
4872
- * after a bound. This is influenced by whether the position is just before or
4873
- * just after the provided values.
4874
- */
4875
- class Bound {
4876
- constructor(position, inclusive) {
4877
- this.position = position;
4878
- this.inclusive = inclusive;
4780
+ inorderTraversal(action) {
4781
+ return false;
4879
4782
  }
4880
- }
4881
- /**
4882
- * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
4883
- */
4884
- class OrderBy {
4885
- constructor(field, dir = "asc" /* ASCENDING */) {
4886
- this.field = field;
4887
- this.dir = dir;
4783
+ reverseTraversal(action) {
4784
+ return false;
4888
4785
  }
4889
- }
4890
- function canonifyOrderBy(orderBy) {
4891
- // TODO(b/29183165): Make this collision robust.
4892
- return orderBy.field.canonicalString() + orderBy.dir;
4893
- }
4894
- function stringifyOrderBy(orderBy) {
4895
- return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
4896
- }
4897
- function orderByEquals(left, right) {
4898
- return left.dir === right.dir && left.field.isEqual(right.field);
4899
- }
4900
- function boundCompareToDocument(bound, orderBy, doc) {
4901
- let comparison = 0;
4902
- for (let i = 0; i < bound.position.length; i++) {
4903
- const orderByComponent = orderBy[i];
4904
- const component = bound.position[i];
4905
- if (orderByComponent.field.isKeyField()) {
4906
- comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
4907
- }
4908
- else {
4909
- const docValue = doc.data.field(orderByComponent.field);
4910
- comparison = valueCompare(component, docValue);
4911
- }
4912
- if (orderByComponent.dir === "desc" /* DESCENDING */) {
4913
- comparison = comparison * -1;
4914
- }
4915
- if (comparison !== 0) {
4916
- break;
4917
- }
4786
+ minKey() {
4787
+ return null;
4918
4788
  }
4919
- return comparison;
4920
- }
4921
- /**
4922
- * Returns true if a document sorts after a bound using the provided sort
4923
- * order.
4924
- */
4925
- function boundSortsAfterDocument(bound, orderBy, doc) {
4926
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4927
- return bound.inclusive ? comparison >= 0 : comparison > 0;
4928
- }
4929
- /**
4930
- * Returns true if a document sorts before a bound using the provided sort
4931
- * order.
4932
- */
4933
- function boundSortsBeforeDocument(bound, orderBy, doc) {
4934
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4935
- return bound.inclusive ? comparison <= 0 : comparison < 0;
4936
- }
4937
- function boundEquals(left, right) {
4938
- if (left === null) {
4939
- return right === null;
4789
+ maxKey() {
4790
+ return null;
4940
4791
  }
4941
- else if (right === null) {
4792
+ isRed() {
4942
4793
  return false;
4943
4794
  }
4944
- if (left.inclusive !== right.inclusive ||
4945
- left.position.length !== right.position.length) {
4946
- return false;
4795
+ // For testing.
4796
+ checkMaxDepth() {
4797
+ return true;
4947
4798
  }
4948
- for (let i = 0; i < left.position.length; i++) {
4949
- const leftPosition = left.position[i];
4950
- const rightPosition = right.position[i];
4951
- if (!valueEquals(leftPosition, rightPosition)) {
4952
- return false;
4953
- }
4799
+ check() {
4800
+ return 0;
4954
4801
  }
4955
- return true;
4956
- }
4802
+ } // end LLRBEmptyNode
4803
+ LLRBNode.EMPTY = new LLRBEmptyNode();
4957
4804
 
4958
4805
  /**
4959
4806
  * @license
@@ -4972,325 +4819,223 @@ function boundEquals(left, right) {
4972
4819
  * limitations under the License.
4973
4820
  */
4974
4821
  /**
4975
- * Query encapsulates all the query attributes we support in the SDK. It can
4976
- * be run against the LocalStore, as well as be converted to a `Target` to
4977
- * query the RemoteStore results.
4822
+ * SortedSet is an immutable (copy-on-write) collection that holds elements
4823
+ * in order specified by the provided comparator.
4978
4824
  *
4979
- * Visible for testing.
4825
+ * NOTE: if provided comparator returns 0 for two elements, we consider them to
4826
+ * be equal!
4980
4827
  */
4981
- class QueryImpl {
4982
- /**
4983
- * Initializes a Query with a path and optional additional query constraints.
4984
- * Path must currently be empty if this is a collection group query.
4985
- */
4986
- constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
4987
- this.path = path;
4988
- this.collectionGroup = collectionGroup;
4989
- this.explicitOrderBy = explicitOrderBy;
4990
- this.filters = filters;
4991
- this.limit = limit;
4992
- this.limitType = limitType;
4993
- this.startAt = startAt;
4994
- this.endAt = endAt;
4995
- this.memoizedOrderBy = null;
4996
- // The corresponding `Target` of this `Query` instance.
4997
- this.memoizedTarget = null;
4998
- if (this.startAt) ;
4999
- if (this.endAt) ;
4828
+ class SortedSet {
4829
+ constructor(comparator) {
4830
+ this.comparator = comparator;
4831
+ this.data = new SortedMap(this.comparator);
5000
4832
  }
5001
- }
5002
- /** Creates a new Query instance with the options provided. */
5003
- function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
5004
- return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
5005
- }
5006
- /** Creates a new Query for a query that matches all documents at `path` */
5007
- function newQueryForPath(path) {
5008
- return new QueryImpl(path);
5009
- }
5010
- /**
5011
- * Helper to convert a collection group query into a collection query at a
5012
- * specific path. This is used when executing collection group queries, since
5013
- * we have to split the query into a set of collection queries at multiple
5014
- * paths.
5015
- */
5016
- function asCollectionQueryAtPath(query, path) {
5017
- return new QueryImpl(path,
5018
- /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5019
- }
5020
- /**
5021
- * Returns true if this query does not specify any query constraints that
5022
- * could remove results.
5023
- */
5024
- function matchesAllDocuments(query) {
5025
- return (query.filters.length === 0 &&
5026
- query.limit === null &&
5027
- query.startAt == null &&
5028
- query.endAt == null &&
5029
- (query.explicitOrderBy.length === 0 ||
5030
- (query.explicitOrderBy.length === 1 &&
5031
- query.explicitOrderBy[0].field.isKeyField())));
5032
- }
5033
- function hasLimitToFirst(query) {
5034
- return !isNullOrUndefined(query.limit) && query.limitType === "F" /* First */;
5035
- }
5036
- function hasLimitToLast(query) {
5037
- return !isNullOrUndefined(query.limit) && query.limitType === "L" /* Last */;
5038
- }
5039
- function getFirstOrderByField(query) {
5040
- return query.explicitOrderBy.length > 0
5041
- ? query.explicitOrderBy[0].field
5042
- : null;
5043
- }
5044
- function getInequalityFilterField(query) {
5045
- for (const filter of query.filters) {
5046
- if (filter.isInequality()) {
5047
- return filter.field;
5048
- }
4833
+ has(elem) {
4834
+ return this.data.get(elem) !== null;
5049
4835
  }
5050
- return null;
5051
- }
5052
- /**
5053
- * Checks if any of the provided Operators are included in the query and
5054
- * returns the first one that is, or null if none are.
5055
- */
5056
- function findFilterOperator(query, operators) {
5057
- for (const filter of query.filters) {
5058
- if (operators.indexOf(filter.op) >= 0) {
5059
- return filter.op;
4836
+ first() {
4837
+ return this.data.minKey();
4838
+ }
4839
+ last() {
4840
+ return this.data.maxKey();
4841
+ }
4842
+ get size() {
4843
+ return this.data.size;
4844
+ }
4845
+ indexOf(elem) {
4846
+ return this.data.indexOf(elem);
4847
+ }
4848
+ /** Iterates elements in order defined by "comparator" */
4849
+ forEach(cb) {
4850
+ this.data.inorderTraversal((k, v) => {
4851
+ cb(k);
4852
+ return false;
4853
+ });
4854
+ }
4855
+ /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
4856
+ forEachInRange(range, cb) {
4857
+ const iter = this.data.getIteratorFrom(range[0]);
4858
+ while (iter.hasNext()) {
4859
+ const elem = iter.getNext();
4860
+ if (this.comparator(elem.key, range[1]) >= 0) {
4861
+ return;
4862
+ }
4863
+ cb(elem.key);
5060
4864
  }
5061
4865
  }
5062
- return null;
5063
- }
5064
- /**
5065
- * Creates a new Query for a collection group query that matches all documents
5066
- * within the provided collection group.
5067
- */
5068
- function newQueryForCollectionGroup(collectionId) {
5069
- return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5070
- }
5071
- /**
5072
- * Returns whether the query matches a single document by path (rather than a
5073
- * collection).
5074
- */
5075
- function isDocumentQuery$1(query) {
5076
- return (DocumentKey.isDocumentKey(query.path) &&
5077
- query.collectionGroup === null &&
5078
- query.filters.length === 0);
5079
- }
5080
- /**
5081
- * Returns whether the query matches a collection group rather than a specific
5082
- * collection.
5083
- */
5084
- function isCollectionGroupQuery(query) {
5085
- return query.collectionGroup !== null;
5086
- }
5087
- /**
5088
- * Returns the implicit order by constraint that is used to execute the Query,
5089
- * which can be different from the order by constraints the user provided (e.g.
5090
- * the SDK and backend always orders by `__name__`).
5091
- */
5092
- function queryOrderBy(query) {
5093
- const queryImpl = debugCast(query);
5094
- if (queryImpl.memoizedOrderBy === null) {
5095
- queryImpl.memoizedOrderBy = [];
5096
- const inequalityField = getInequalityFilterField(queryImpl);
5097
- const firstOrderByField = getFirstOrderByField(queryImpl);
5098
- if (inequalityField !== null && firstOrderByField === null) {
5099
- // In order to implicitly add key ordering, we must also add the
5100
- // inequality filter field for it to be a valid query.
5101
- // Note that the default inequality field and key ordering is ascending.
5102
- if (!inequalityField.isKeyField()) {
5103
- queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5104
- }
5105
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
4866
+ /**
4867
+ * Iterates over `elem`s such that: start &lt;= elem until false is returned.
4868
+ */
4869
+ forEachWhile(cb, start) {
4870
+ let iter;
4871
+ if (start !== undefined) {
4872
+ iter = this.data.getIteratorFrom(start);
5106
4873
  }
5107
4874
  else {
5108
- let foundKeyOrdering = false;
5109
- for (const orderBy of queryImpl.explicitOrderBy) {
5110
- queryImpl.memoizedOrderBy.push(orderBy);
5111
- if (orderBy.field.isKeyField()) {
5112
- foundKeyOrdering = true;
5113
- }
5114
- }
5115
- if (!foundKeyOrdering) {
5116
- // The order of the implicit key ordering always matches the last
5117
- // explicit order by
5118
- const lastDirection = queryImpl.explicitOrderBy.length > 0
5119
- ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5120
- .dir
5121
- : "asc" /* ASCENDING */;
5122
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
5123
- }
5124
- }
5125
- }
5126
- return queryImpl.memoizedOrderBy;
5127
- }
5128
- /**
5129
- * Converts this `Query` instance to it's corresponding `Target` representation.
5130
- */
5131
- function queryToTarget(query) {
5132
- const queryImpl = debugCast(query);
5133
- if (!queryImpl.memoizedTarget) {
5134
- if (queryImpl.limitType === "F" /* First */) {
5135
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
4875
+ iter = this.data.getIterator();
5136
4876
  }
5137
- else {
5138
- // Flip the orderBy directions since we want the last results
5139
- const orderBys = [];
5140
- for (const orderBy of queryOrderBy(queryImpl)) {
5141
- const dir = orderBy.dir === "desc" /* DESCENDING */
5142
- ? "asc" /* ASCENDING */
5143
- : "desc" /* DESCENDING */;
5144
- orderBys.push(new OrderBy(orderBy.field, dir));
4877
+ while (iter.hasNext()) {
4878
+ const elem = iter.getNext();
4879
+ const result = cb(elem.key);
4880
+ if (!result) {
4881
+ return;
5145
4882
  }
5146
- // We need to swap the cursors to match the now-flipped query ordering.
5147
- const startAt = queryImpl.endAt
5148
- ? new Bound(queryImpl.endAt.position, !queryImpl.endAt.inclusive)
5149
- : null;
5150
- const endAt = queryImpl.startAt
5151
- ? new Bound(queryImpl.startAt.position, !queryImpl.startAt.inclusive)
5152
- : null;
5153
- // Now return as a LimitType.First query.
5154
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5155
4883
  }
5156
4884
  }
5157
- return queryImpl.memoizedTarget;
5158
- }
5159
- function queryWithAddedFilter(query, filter) {
5160
- const newFilters = query.filters.concat([filter]);
5161
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5162
- }
5163
- function queryWithAddedOrderBy(query, orderBy) {
5164
- // TODO(dimond): validate that orderBy does not list the same key twice.
5165
- const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5166
- return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5167
- }
5168
- function queryWithLimit(query, limit, limitType) {
5169
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5170
- }
5171
- function queryWithStartAt(query, bound) {
5172
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5173
- }
5174
- function queryWithEndAt(query, bound) {
5175
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5176
- }
5177
- function queryEquals(left, right) {
5178
- return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5179
- left.limitType === right.limitType);
5180
- }
5181
- // TODO(b/29183165): This is used to get a unique string from a query to, for
5182
- // example, use as a dictionary key, but the implementation is subject to
5183
- // collisions. Make it collision-free.
5184
- function canonifyQuery(query) {
5185
- return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5186
- }
5187
- function stringifyQuery(query) {
5188
- return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5189
- }
5190
- /** Returns whether `doc` matches the constraints of `query`. */
5191
- function queryMatches(query, doc) {
5192
- return (doc.isFoundDocument() &&
5193
- queryMatchesPathAndCollectionGroup(query, doc) &&
5194
- queryMatchesOrderBy(query, doc) &&
5195
- queryMatchesFilters(query, doc) &&
5196
- queryMatchesBounds(query, doc));
5197
- }
5198
- function queryMatchesPathAndCollectionGroup(query, doc) {
5199
- const docPath = doc.key.path;
5200
- if (query.collectionGroup !== null) {
5201
- // NOTE: this.path is currently always empty since we don't expose Collection
5202
- // Group queries rooted at a document path yet.
5203
- return (doc.key.hasCollectionId(query.collectionGroup) &&
5204
- query.path.isPrefixOf(docPath));
4885
+ /** Finds the least element greater than or equal to `elem`. */
4886
+ firstAfterOrEqual(elem) {
4887
+ const iter = this.data.getIteratorFrom(elem);
4888
+ return iter.hasNext() ? iter.getNext().key : null;
5205
4889
  }
5206
- else if (DocumentKey.isDocumentKey(query.path)) {
5207
- // exact match for document queries
5208
- return query.path.isEqual(docPath);
4890
+ getIterator() {
4891
+ return new SortedSetIterator(this.data.getIterator());
5209
4892
  }
5210
- else {
5211
- // shallow ancestor queries by default
5212
- return query.path.isImmediateParentOf(docPath);
4893
+ getIteratorFrom(key) {
4894
+ return new SortedSetIterator(this.data.getIteratorFrom(key));
5213
4895
  }
5214
- }
5215
- /**
5216
- * A document must have a value for every ordering clause in order to show up
5217
- * in the results.
5218
- */
5219
- function queryMatchesOrderBy(query, doc) {
5220
- for (const orderBy of query.explicitOrderBy) {
5221
- // order by key always matches
5222
- if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5223
- return false;
4896
+ /** Inserts or updates an element */
4897
+ add(elem) {
4898
+ return this.copy(this.data.remove(elem).insert(elem, true));
4899
+ }
4900
+ /** Deletes an element */
4901
+ delete(elem) {
4902
+ if (!this.has(elem)) {
4903
+ return this;
5224
4904
  }
4905
+ return this.copy(this.data.remove(elem));
5225
4906
  }
5226
- return true;
5227
- }
5228
- function queryMatchesFilters(query, doc) {
5229
- for (const filter of query.filters) {
5230
- if (!filter.matches(doc)) {
4907
+ isEmpty() {
4908
+ return this.data.isEmpty();
4909
+ }
4910
+ unionWith(other) {
4911
+ let result = this;
4912
+ // Make sure `result` always refers to the larger one of the two sets.
4913
+ if (result.size < other.size) {
4914
+ result = other;
4915
+ other = this;
4916
+ }
4917
+ other.forEach(elem => {
4918
+ result = result.add(elem);
4919
+ });
4920
+ return result;
4921
+ }
4922
+ isEqual(other) {
4923
+ if (!(other instanceof SortedSet)) {
4924
+ return false;
4925
+ }
4926
+ if (this.size !== other.size) {
5231
4927
  return false;
5232
4928
  }
4929
+ const thisIt = this.data.getIterator();
4930
+ const otherIt = other.data.getIterator();
4931
+ while (thisIt.hasNext()) {
4932
+ const thisElem = thisIt.getNext().key;
4933
+ const otherElem = otherIt.getNext().key;
4934
+ if (this.comparator(thisElem, otherElem) !== 0) {
4935
+ return false;
4936
+ }
4937
+ }
4938
+ return true;
4939
+ }
4940
+ toArray() {
4941
+ const res = [];
4942
+ this.forEach(targetId => {
4943
+ res.push(targetId);
4944
+ });
4945
+ return res;
4946
+ }
4947
+ toString() {
4948
+ const result = [];
4949
+ this.forEach(elem => result.push(elem));
4950
+ return 'SortedSet(' + result.toString() + ')';
4951
+ }
4952
+ copy(data) {
4953
+ const result = new SortedSet(this.comparator);
4954
+ result.data = data;
4955
+ return result;
5233
4956
  }
5234
- return true;
5235
4957
  }
5236
- /** Makes sure a document is within the bounds, if provided. */
5237
- function queryMatchesBounds(query, doc) {
5238
- if (query.startAt &&
5239
- !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5240
- return false;
4958
+ class SortedSetIterator {
4959
+ constructor(iter) {
4960
+ this.iter = iter;
5241
4961
  }
5242
- if (query.endAt &&
5243
- !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5244
- return false;
4962
+ getNext() {
4963
+ return this.iter.getNext().key;
4964
+ }
4965
+ hasNext() {
4966
+ return this.iter.hasNext();
5245
4967
  }
5246
- return true;
5247
4968
  }
5248
4969
  /**
5249
- * Returns the collection group that this query targets.
4970
+ * Compares two sorted sets for equality using their natural ordering. The
4971
+ * method computes the intersection and invokes `onAdd` for every element that
4972
+ * is in `after` but not `before`. `onRemove` is invoked for every element in
4973
+ * `before` but missing from `after`.
5250
4974
  *
5251
- * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5252
- * synchronization for query results.
5253
- */
5254
- function queryCollectionGroup(query) {
5255
- return (query.collectionGroup ||
5256
- (query.path.length % 2 === 1
5257
- ? query.path.lastSegment()
5258
- : query.path.get(query.path.length - 2)));
5259
- }
5260
- /**
5261
- * Returns a new comparator function that can be used to compare two documents
5262
- * based on the Query's ordering constraint.
4975
+ * The method creates a copy of both `before` and `after` and runs in O(n log
4976
+ * n), where n is the size of the two lists.
4977
+ *
4978
+ * @param before - The elements that exist in the original set.
4979
+ * @param after - The elements to diff against the original set.
4980
+ * @param comparator - The comparator for the elements in before and after.
4981
+ * @param onAdd - A function to invoke for every element that is part of `
4982
+ * after` but not `before`.
4983
+ * @param onRemove - A function to invoke for every element that is part of
4984
+ * `before` but not `after`.
5263
4985
  */
5264
- function newQueryComparator(query) {
5265
- return (d1, d2) => {
5266
- let comparedOnKeyField = false;
5267
- for (const orderBy of queryOrderBy(query)) {
5268
- const comp = compareDocs(orderBy, d1, d2);
5269
- if (comp !== 0) {
5270
- return comp;
4986
+ function diffSortedSets(before, after, comparator, onAdd, onRemove) {
4987
+ const beforeIt = before.getIterator();
4988
+ const afterIt = after.getIterator();
4989
+ let beforeValue = advanceIterator(beforeIt);
4990
+ let afterValue = advanceIterator(afterIt);
4991
+ // Walk through the two sets at the same time, using the ordering defined by
4992
+ // `comparator`.
4993
+ while (beforeValue || afterValue) {
4994
+ let added = false;
4995
+ let removed = false;
4996
+ if (beforeValue && afterValue) {
4997
+ const cmp = comparator(beforeValue, afterValue);
4998
+ if (cmp < 0) {
4999
+ // The element was removed if the next element in our ordered
5000
+ // walkthrough is only in `before`.
5001
+ removed = true;
5002
+ }
5003
+ else if (cmp > 0) {
5004
+ // The element was added if the next element in our ordered walkthrough
5005
+ // is only in `after`.
5006
+ added = true;
5271
5007
  }
5272
- comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
5273
5008
  }
5274
- return 0;
5275
- };
5276
- }
5277
- function compareDocs(orderBy, d1, d2) {
5278
- const comparison = orderBy.field.isKeyField()
5279
- ? DocumentKey.comparator(d1.key, d2.key)
5280
- : compareDocumentsByField(orderBy.field, d1, d2);
5281
- switch (orderBy.dir) {
5282
- case "asc" /* ASCENDING */:
5283
- return comparison;
5284
- case "desc" /* DESCENDING */:
5285
- return -1 * comparison;
5286
- default:
5287
- return fail();
5009
+ else if (beforeValue != null) {
5010
+ removed = true;
5011
+ }
5012
+ else {
5013
+ added = true;
5014
+ }
5015
+ if (added) {
5016
+ onAdd(afterValue);
5017
+ afterValue = advanceIterator(afterIt);
5018
+ }
5019
+ else if (removed) {
5020
+ onRemove(beforeValue);
5021
+ beforeValue = advanceIterator(beforeIt);
5022
+ }
5023
+ else {
5024
+ beforeValue = advanceIterator(beforeIt);
5025
+ afterValue = advanceIterator(afterIt);
5026
+ }
5288
5027
  }
5028
+ }
5029
+ /**
5030
+ * Returns the next element from the iterator or `undefined` if none available.
5031
+ */
5032
+ function advanceIterator(it) {
5033
+ return it.hasNext() ? it.getNext() : undefined;
5289
5034
  }
5290
5035
 
5291
5036
  /**
5292
5037
  * @license
5293
- * Copyright 2017 Google LLC
5038
+ * Copyright 2019 Google LLC
5294
5039
  *
5295
5040
  * Licensed under the Apache License, Version 2.0 (the "License");
5296
5041
  * you may not use this file except in compliance with the License.
@@ -5304,555 +5049,961 @@ function compareDocs(orderBy, d1, d2) {
5304
5049
  * See the License for the specific language governing permissions and
5305
5050
  * limitations under the License.
5306
5051
  */
5052
+ // Visible for testing
5053
+ class TargetImpl {
5054
+ constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5055
+ this.path = path;
5056
+ this.collectionGroup = collectionGroup;
5057
+ this.orderBy = orderBy;
5058
+ this.filters = filters;
5059
+ this.limit = limit;
5060
+ this.startAt = startAt;
5061
+ this.endAt = endAt;
5062
+ this.memoizedCanonicalId = null;
5063
+ }
5064
+ }
5307
5065
  /**
5308
- * A map implementation that uses objects as keys. Objects must have an
5309
- * associated equals function and must be immutable. Entries in the map are
5310
- * stored together with the key being produced from the mapKeyFn. This map
5311
- * automatically handles collisions of keys.
5066
+ * Initializes a Target with a path and optional additional query constraints.
5067
+ * Path must currently be empty if this is a collection group query.
5068
+ *
5069
+ * NOTE: you should always construct `Target` from `Query.toTarget` instead of
5070
+ * using this factory method, because `Query` provides an implicit `orderBy`
5071
+ * property.
5312
5072
  */
5313
- class ObjectMap {
5314
- constructor(mapKeyFn, equalsFn) {
5315
- this.mapKeyFn = mapKeyFn;
5316
- this.equalsFn = equalsFn;
5317
- /**
5318
- * The inner map for a key/value pair. Due to the possibility of collisions we
5319
- * keep a list of entries that we do a linear search through to find an actual
5320
- * match. Note that collisions should be rare, so we still expect near
5321
- * constant time lookups in practice.
5322
- */
5323
- this.inner = {};
5324
- /** The number of entries stored in the map */
5325
- this.innerSize = 0;
5326
- }
5327
- /** Get a value for this key, or undefined if it does not exist. */
5328
- get(key) {
5329
- const id = this.mapKeyFn(key);
5330
- const matches = this.inner[id];
5331
- if (matches === undefined) {
5332
- return undefined;
5073
+ function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5074
+ return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
5075
+ }
5076
+ function canonifyTarget(target) {
5077
+ const targetImpl = debugCast(target);
5078
+ if (targetImpl.memoizedCanonicalId === null) {
5079
+ let str = targetImpl.path.canonicalString();
5080
+ if (targetImpl.collectionGroup !== null) {
5081
+ str += '|cg:' + targetImpl.collectionGroup;
5333
5082
  }
5334
- for (const [otherKey, value] of matches) {
5335
- if (this.equalsFn(otherKey, key)) {
5336
- return value;
5337
- }
5083
+ str += '|f:';
5084
+ str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
5085
+ str += '|ob:';
5086
+ str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
5087
+ if (!isNullOrUndefined(targetImpl.limit)) {
5088
+ str += '|l:';
5089
+ str += targetImpl.limit;
5338
5090
  }
5339
- return undefined;
5340
- }
5341
- has(key) {
5342
- return this.get(key) !== undefined;
5343
- }
5344
- /** Put this key and value in the map. */
5345
- set(key, value) {
5346
- const id = this.mapKeyFn(key);
5347
- const matches = this.inner[id];
5348
- if (matches === undefined) {
5349
- this.inner[id] = [[key, value]];
5350
- this.innerSize++;
5351
- return;
5091
+ if (targetImpl.startAt) {
5092
+ str += '|lb:';
5093
+ str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
5094
+ str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
5352
5095
  }
5353
- for (let i = 0; i < matches.length; i++) {
5354
- if (this.equalsFn(matches[i][0], key)) {
5355
- // This is updating an existing entry and does not increase `innerSize`.
5356
- matches[i] = [key, value];
5357
- return;
5358
- }
5096
+ if (targetImpl.endAt) {
5097
+ str += '|ub:';
5098
+ str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
5099
+ str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
5359
5100
  }
5360
- matches.push([key, value]);
5361
- this.innerSize++;
5101
+ targetImpl.memoizedCanonicalId = str;
5362
5102
  }
5363
- /**
5364
- * Remove this key from the map. Returns a boolean if anything was deleted.
5365
- */
5366
- delete(key) {
5367
- const id = this.mapKeyFn(key);
5368
- const matches = this.inner[id];
5369
- if (matches === undefined) {
5103
+ return targetImpl.memoizedCanonicalId;
5104
+ }
5105
+ function stringifyTarget(target) {
5106
+ let str = target.path.canonicalString();
5107
+ if (target.collectionGroup !== null) {
5108
+ str += ' collectionGroup=' + target.collectionGroup;
5109
+ }
5110
+ if (target.filters.length > 0) {
5111
+ str += `, filters: [${target.filters
5112
+ .map(f => stringifyFilter(f))
5113
+ .join(', ')}]`;
5114
+ }
5115
+ if (!isNullOrUndefined(target.limit)) {
5116
+ str += ', limit: ' + target.limit;
5117
+ }
5118
+ if (target.orderBy.length > 0) {
5119
+ str += `, orderBy: [${target.orderBy
5120
+ .map(o => stringifyOrderBy(o))
5121
+ .join(', ')}]`;
5122
+ }
5123
+ if (target.startAt) {
5124
+ str += ', startAt: ';
5125
+ str += target.startAt.inclusive ? 'b:' : 'a:';
5126
+ str += target.startAt.position.map(p => canonicalId(p)).join(',');
5127
+ }
5128
+ if (target.endAt) {
5129
+ str += ', endAt: ';
5130
+ str += target.endAt.inclusive ? 'a:' : 'b:';
5131
+ str += target.endAt.position.map(p => canonicalId(p)).join(',');
5132
+ }
5133
+ return `Target(${str})`;
5134
+ }
5135
+ function targetEquals(left, right) {
5136
+ if (left.limit !== right.limit) {
5137
+ return false;
5138
+ }
5139
+ if (left.orderBy.length !== right.orderBy.length) {
5140
+ return false;
5141
+ }
5142
+ for (let i = 0; i < left.orderBy.length; i++) {
5143
+ if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
5370
5144
  return false;
5371
5145
  }
5372
- for (let i = 0; i < matches.length; i++) {
5373
- if (this.equalsFn(matches[i][0], key)) {
5374
- if (matches.length === 1) {
5375
- delete this.inner[id];
5376
- }
5377
- else {
5378
- matches.splice(i, 1);
5379
- }
5380
- this.innerSize--;
5381
- return true;
5382
- }
5383
- }
5146
+ }
5147
+ if (left.filters.length !== right.filters.length) {
5384
5148
  return false;
5385
5149
  }
5386
- forEach(fn) {
5387
- forEach(this.inner, (_, entries) => {
5388
- for (const [k, v] of entries) {
5389
- fn(k, v);
5390
- }
5391
- });
5150
+ for (let i = 0; i < left.filters.length; i++) {
5151
+ if (!filterEquals(left.filters[i], right.filters[i])) {
5152
+ return false;
5153
+ }
5392
5154
  }
5393
- isEmpty() {
5394
- return isEmpty(this.inner);
5155
+ if (left.collectionGroup !== right.collectionGroup) {
5156
+ return false;
5395
5157
  }
5396
- size() {
5397
- return this.innerSize;
5158
+ if (!left.path.isEqual(right.path)) {
5159
+ return false;
5398
5160
  }
5399
- }
5400
-
5161
+ if (!boundEquals(left.startAt, right.startAt)) {
5162
+ return false;
5163
+ }
5164
+ return boundEquals(left.endAt, right.endAt);
5165
+ }
5166
+ function targetIsDocumentTarget(target) {
5167
+ return (DocumentKey.isDocumentKey(target.path) &&
5168
+ target.collectionGroup === null &&
5169
+ target.filters.length === 0);
5170
+ }
5171
+ /** Returns the field filters that target the given field path. */
5172
+ function targetGetFieldFiltersForPath(target, path) {
5173
+ return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
5174
+ }
5401
5175
  /**
5402
- * @license
5403
- * Copyright 2017 Google LLC
5404
- *
5405
- * Licensed under the Apache License, Version 2.0 (the "License");
5406
- * you may not use this file except in compliance with the License.
5407
- * You may obtain a copy of the License at
5408
- *
5409
- * http://www.apache.org/licenses/LICENSE-2.0
5410
- *
5411
- * Unless required by applicable law or agreed to in writing, software
5412
- * distributed under the License is distributed on an "AS IS" BASIS,
5413
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5414
- * See the License for the specific language governing permissions and
5415
- * limitations under the License.
5176
+ * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
5177
+ * filters. Returns `null` if there are no such filters.
5416
5178
  */
5417
- // An immutable sorted map implementation, based on a Left-leaning Red-Black
5418
- // tree.
5419
- class SortedMap {
5420
- constructor(comparator, root) {
5421
- this.comparator = comparator;
5422
- this.root = root ? root : LLRBNode.EMPTY;
5423
- }
5424
- // Returns a copy of the map, with the specified key/value added or replaced.
5425
- insert(key, value) {
5426
- return new SortedMap(this.comparator, this.root
5427
- .insert(key, value, this.comparator)
5428
- .copy(null, null, LLRBNode.BLACK, null, null));
5429
- }
5430
- // Returns a copy of the map, with the specified key removed.
5431
- remove(key) {
5432
- return new SortedMap(this.comparator, this.root
5433
- .remove(key, this.comparator)
5434
- .copy(null, null, LLRBNode.BLACK, null, null));
5179
+ function targetGetArrayValues(target, fieldIndex) {
5180
+ const segment = fieldIndexGetArraySegment(fieldIndex);
5181
+ if (segment === undefined) {
5182
+ return null;
5435
5183
  }
5436
- // Returns the value of the node with the given key, or null.
5437
- get(key) {
5438
- let node = this.root;
5439
- while (!node.isEmpty()) {
5440
- const cmp = this.comparator(key, node.key);
5441
- if (cmp === 0) {
5442
- return node.value;
5443
- }
5444
- else if (cmp < 0) {
5445
- node = node.left;
5446
- }
5447
- else if (cmp > 0) {
5448
- node = node.right;
5449
- }
5184
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5185
+ switch (fieldFilter.op) {
5186
+ case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
5187
+ return fieldFilter.value.arrayValue.values || [];
5188
+ case "array-contains" /* ARRAY_CONTAINS */:
5189
+ return [fieldFilter.value];
5190
+ // Remaining filters are not array filters.
5450
5191
  }
5451
- return null;
5452
5192
  }
5453
- // Returns the index of the element in this sorted map, or -1 if it doesn't
5454
- // exist.
5455
- indexOf(key) {
5456
- // Number of nodes that were pruned when descending right
5457
- let prunedNodes = 0;
5458
- let node = this.root;
5459
- while (!node.isEmpty()) {
5460
- const cmp = this.comparator(key, node.key);
5461
- if (cmp === 0) {
5462
- return prunedNodes + node.left.size;
5463
- }
5464
- else if (cmp < 0) {
5465
- node = node.left;
5466
- }
5467
- else {
5468
- // Count all nodes left of the node plus the node itself
5469
- prunedNodes += node.left.size + 1;
5470
- node = node.right;
5193
+ return null;
5194
+ }
5195
+ /**
5196
+ * Returns the list of values that are used in != or NOT_IN filters. Returns
5197
+ * `null` if there are no such filters.
5198
+ */
5199
+ function targetGetNotInValues(target, fieldIndex) {
5200
+ const values = new Map();
5201
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5202
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5203
+ switch (fieldFilter.op) {
5204
+ case "==" /* EQUAL */:
5205
+ case "in" /* IN */:
5206
+ // Encode equality prefix, which is encoded in the index value before
5207
+ // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
5208
+ // `value != 'ab'`).
5209
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5210
+ break;
5211
+ case "not-in" /* NOT_IN */:
5212
+ case "!=" /* NOT_EQUAL */:
5213
+ // NotIn/NotEqual is always a suffix. There cannot be any remaining
5214
+ // segments and hence we can return early here.
5215
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5216
+ return Array.from(values.values());
5217
+ // Remaining filters cannot be used as notIn bounds.
5471
5218
  }
5472
5219
  }
5473
- // Node not found
5474
- return -1;
5475
- }
5476
- isEmpty() {
5477
- return this.root.isEmpty();
5478
- }
5479
- // Returns the total number of nodes in the map.
5480
- get size() {
5481
- return this.root.size;
5482
5220
  }
5483
- // Returns the minimum key in the map.
5484
- minKey() {
5485
- return this.root.minKey();
5486
- }
5487
- // Returns the maximum key in the map.
5488
- maxKey() {
5489
- return this.root.maxKey();
5221
+ return null;
5222
+ }
5223
+ /**
5224
+ * Returns a lower bound of field values that can be used as a starting point to
5225
+ * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
5226
+ * exists.
5227
+ */
5228
+ function targetGetLowerBound(target, fieldIndex) {
5229
+ const values = [];
5230
+ let inclusive = true;
5231
+ // For each segment, retrieve a lower bound if there is a suitable filter or
5232
+ // startAt.
5233
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5234
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5235
+ ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)
5236
+ : targetGetDescendingBound(target, segment.fieldPath, target.startAt);
5237
+ values.push(segmentBound.value);
5238
+ inclusive && (inclusive = segmentBound.inclusive);
5490
5239
  }
5491
- // Traverses the map in key order and calls the specified action function
5492
- // for each key/value pair. If action returns true, traversal is aborted.
5493
- // Returns the first truthy value returned by action, or the last falsey
5494
- // value returned by action.
5495
- inorderTraversal(action) {
5496
- return this.root.inorderTraversal(action);
5240
+ return new Bound(values, inclusive);
5241
+ }
5242
+ /**
5243
+ * Returns an upper bound of field values that can be used as an ending point
5244
+ * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
5245
+ * upper bound exists.
5246
+ */
5247
+ function targetGetUpperBound(target, fieldIndex) {
5248
+ const values = [];
5249
+ let inclusive = true;
5250
+ // For each segment, retrieve an upper bound if there is a suitable filter or
5251
+ // endAt.
5252
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5253
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5254
+ ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)
5255
+ : targetGetAscendingBound(target, segment.fieldPath, target.endAt);
5256
+ values.push(segmentBound.value);
5257
+ inclusive && (inclusive = segmentBound.inclusive);
5497
5258
  }
5498
- forEach(fn) {
5499
- this.inorderTraversal((k, v) => {
5500
- fn(k, v);
5501
- return false;
5502
- });
5259
+ return new Bound(values, inclusive);
5260
+ }
5261
+ /**
5262
+ * Returns the value to use as the lower bound for ascending index segment at
5263
+ * the provided `fieldPath` (or the upper bound for an descending segment).
5264
+ */
5265
+ function targetGetAscendingBound(target, fieldPath, bound) {
5266
+ let value = MIN_VALUE;
5267
+ let inclusive = true;
5268
+ // Process all filters to find a value for the current field segment
5269
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5270
+ let filterValue = MIN_VALUE;
5271
+ let filterInclusive = true;
5272
+ switch (fieldFilter.op) {
5273
+ case "<" /* LESS_THAN */:
5274
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5275
+ filterValue = valuesGetLowerBound(fieldFilter.value);
5276
+ break;
5277
+ case "==" /* EQUAL */:
5278
+ case "in" /* IN */:
5279
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5280
+ filterValue = fieldFilter.value;
5281
+ break;
5282
+ case ">" /* GREATER_THAN */:
5283
+ filterValue = fieldFilter.value;
5284
+ filterInclusive = false;
5285
+ break;
5286
+ case "!=" /* NOT_EQUAL */:
5287
+ case "not-in" /* NOT_IN */:
5288
+ filterValue = MIN_VALUE;
5289
+ break;
5290
+ // Remaining filters cannot be used as lower bounds.
5291
+ }
5292
+ if (lowerBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) < 0) {
5293
+ value = filterValue;
5294
+ inclusive = filterInclusive;
5295
+ }
5503
5296
  }
5504
- toString() {
5505
- const descriptions = [];
5506
- this.inorderTraversal((k, v) => {
5507
- descriptions.push(`${k}:${v}`);
5508
- return false;
5509
- });
5510
- return `{${descriptions.join(', ')}}`;
5297
+ // If there is an additional bound, compare the values against the existing
5298
+ // range to see if we can narrow the scope.
5299
+ if (bound !== null) {
5300
+ for (let i = 0; i < target.orderBy.length; ++i) {
5301
+ const orderBy = target.orderBy[i];
5302
+ if (orderBy.field.isEqual(fieldPath)) {
5303
+ const cursorValue = bound.position[i];
5304
+ if (lowerBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) < 0) {
5305
+ value = cursorValue;
5306
+ inclusive = bound.inclusive;
5307
+ }
5308
+ break;
5309
+ }
5310
+ }
5511
5311
  }
5512
- // Traverses the map in reverse key order and calls the specified action
5513
- // function for each key/value pair. If action returns true, traversal is
5514
- // aborted.
5515
- // Returns the first truthy value returned by action, or the last falsey
5516
- // value returned by action.
5517
- reverseTraversal(action) {
5518
- return this.root.reverseTraversal(action);
5312
+ return { value, inclusive };
5313
+ }
5314
+ /**
5315
+ * Returns the value to use as the upper bound for ascending index segment at
5316
+ * the provided `fieldPath` (or the lower bound for a descending segment).
5317
+ */
5318
+ function targetGetDescendingBound(target, fieldPath, bound) {
5319
+ let value = MAX_VALUE;
5320
+ let inclusive = true;
5321
+ // Process all filters to find a value for the current field segment
5322
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5323
+ let filterValue = MAX_VALUE;
5324
+ let filterInclusive = true;
5325
+ switch (fieldFilter.op) {
5326
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5327
+ case ">" /* GREATER_THAN */:
5328
+ filterValue = valuesGetUpperBound(fieldFilter.value);
5329
+ filterInclusive = false;
5330
+ break;
5331
+ case "==" /* EQUAL */:
5332
+ case "in" /* IN */:
5333
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5334
+ filterValue = fieldFilter.value;
5335
+ break;
5336
+ case "<" /* LESS_THAN */:
5337
+ filterValue = fieldFilter.value;
5338
+ filterInclusive = false;
5339
+ break;
5340
+ case "!=" /* NOT_EQUAL */:
5341
+ case "not-in" /* NOT_IN */:
5342
+ filterValue = MAX_VALUE;
5343
+ break;
5344
+ // Remaining filters cannot be used as upper bounds.
5345
+ }
5346
+ if (upperBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) > 0) {
5347
+ value = filterValue;
5348
+ inclusive = filterInclusive;
5349
+ }
5519
5350
  }
5520
- // Returns an iterator over the SortedMap.
5521
- getIterator() {
5522
- return new SortedMapIterator(this.root, null, this.comparator, false);
5351
+ // If there is an additional bound, compare the values against the existing
5352
+ // range to see if we can narrow the scope.
5353
+ if (bound !== null) {
5354
+ for (let i = 0; i < target.orderBy.length; ++i) {
5355
+ const orderBy = target.orderBy[i];
5356
+ if (orderBy.field.isEqual(fieldPath)) {
5357
+ const cursorValue = bound.position[i];
5358
+ if (upperBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) > 0) {
5359
+ value = cursorValue;
5360
+ inclusive = bound.inclusive;
5361
+ }
5362
+ break;
5363
+ }
5364
+ }
5523
5365
  }
5524
- getIteratorFrom(key) {
5525
- return new SortedMapIterator(this.root, key, this.comparator, false);
5366
+ return { value, inclusive };
5367
+ }
5368
+ /** Returns the number of segments of a perfect index for this target. */
5369
+ function targetGetSegmentCount(target) {
5370
+ let fields = new SortedSet(FieldPath$1.comparator);
5371
+ let hasArraySegment = false;
5372
+ for (const filter of target.filters) {
5373
+ // TODO(orquery): Use the flattened filters here
5374
+ const fieldFilter = filter;
5375
+ // __name__ is not an explicit segment of any index, so we don't need to
5376
+ // count it.
5377
+ if (fieldFilter.field.isKeyField()) {
5378
+ continue;
5379
+ }
5380
+ // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
5381
+ // For instance, it is possible to have an index for "a ARRAY a ASC". Even
5382
+ // though these are on the same field, they should be counted as two
5383
+ // separate segments in an index.
5384
+ if (fieldFilter.op === "array-contains" /* ARRAY_CONTAINS */ ||
5385
+ fieldFilter.op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5386
+ hasArraySegment = true;
5387
+ }
5388
+ else {
5389
+ fields = fields.add(fieldFilter.field);
5390
+ }
5526
5391
  }
5527
- getReverseIterator() {
5528
- return new SortedMapIterator(this.root, null, this.comparator, true);
5392
+ for (const orderBy of target.orderBy) {
5393
+ // __name__ is not an explicit segment of any index, so we don't need to
5394
+ // count it.
5395
+ if (!orderBy.field.isKeyField()) {
5396
+ fields = fields.add(orderBy.field);
5397
+ }
5529
5398
  }
5530
- getReverseIteratorFrom(key) {
5531
- return new SortedMapIterator(this.root, key, this.comparator, true);
5399
+ return fields.size + (hasArraySegment ? 1 : 0);
5400
+ }
5401
+ class Filter {
5402
+ }
5403
+ class FieldFilter extends Filter {
5404
+ constructor(field, op, value) {
5405
+ super();
5406
+ this.field = field;
5407
+ this.op = op;
5408
+ this.value = value;
5532
5409
  }
5533
- } // end SortedMap
5534
- // An iterator over an LLRBNode.
5535
- class SortedMapIterator {
5536
- constructor(node, startKey, comparator, isReverse) {
5537
- this.isReverse = isReverse;
5538
- this.nodeStack = [];
5539
- let cmp = 1;
5540
- while (!node.isEmpty()) {
5541
- cmp = startKey ? comparator(node.key, startKey) : 1;
5542
- // flip the comparison if we're going in reverse
5543
- if (startKey && isReverse) {
5544
- cmp *= -1;
5545
- }
5546
- if (cmp < 0) {
5547
- // This node is less than our start key. ignore it
5548
- if (this.isReverse) {
5549
- node = node.left;
5550
- }
5551
- else {
5552
- node = node.right;
5553
- }
5554
- }
5555
- else if (cmp === 0) {
5556
- // This node is exactly equal to our start key. Push it on the stack,
5557
- // but stop iterating;
5558
- this.nodeStack.push(node);
5559
- break;
5410
+ /**
5411
+ * Creates a filter based on the provided arguments.
5412
+ */
5413
+ static create(field, op, value) {
5414
+ if (field.isKeyField()) {
5415
+ if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
5416
+ return this.createKeyFieldInFilter(field, op, value);
5560
5417
  }
5561
5418
  else {
5562
- // This node is greater than our start key, add it to the stack and move
5563
- // to the next one
5564
- this.nodeStack.push(node);
5565
- if (this.isReverse) {
5566
- node = node.right;
5567
- }
5568
- else {
5569
- node = node.left;
5570
- }
5419
+ return new KeyFieldFilter(field, op, value);
5571
5420
  }
5572
5421
  }
5573
- }
5574
- getNext() {
5575
- let node = this.nodeStack.pop();
5576
- const result = { key: node.key, value: node.value };
5577
- if (this.isReverse) {
5578
- node = node.left;
5579
- while (!node.isEmpty()) {
5580
- this.nodeStack.push(node);
5581
- node = node.right;
5582
- }
5422
+ else if (op === "array-contains" /* ARRAY_CONTAINS */) {
5423
+ return new ArrayContainsFilter(field, value);
5424
+ }
5425
+ else if (op === "in" /* IN */) {
5426
+ return new InFilter(field, value);
5427
+ }
5428
+ else if (op === "not-in" /* NOT_IN */) {
5429
+ return new NotInFilter(field, value);
5430
+ }
5431
+ else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5432
+ return new ArrayContainsAnyFilter(field, value);
5583
5433
  }
5584
5434
  else {
5585
- node = node.right;
5586
- while (!node.isEmpty()) {
5587
- this.nodeStack.push(node);
5588
- node = node.left;
5589
- }
5435
+ return new FieldFilter(field, op, value);
5436
+ }
5437
+ }
5438
+ static createKeyFieldInFilter(field, op, value) {
5439
+ return op === "in" /* IN */
5440
+ ? new KeyFieldInFilter(field, value)
5441
+ : new KeyFieldNotInFilter(field, value);
5442
+ }
5443
+ matches(doc) {
5444
+ const other = doc.data.field(this.field);
5445
+ // Types do not have to match in NOT_EQUAL filters.
5446
+ if (this.op === "!=" /* NOT_EQUAL */) {
5447
+ return (other !== null &&
5448
+ this.matchesComparison(valueCompare(other, this.value)));
5449
+ }
5450
+ // Only compare types with matching backend order (such as double and int).
5451
+ return (other !== null &&
5452
+ typeOrder(this.value) === typeOrder(other) &&
5453
+ this.matchesComparison(valueCompare(other, this.value)));
5454
+ }
5455
+ matchesComparison(comparison) {
5456
+ switch (this.op) {
5457
+ case "<" /* LESS_THAN */:
5458
+ return comparison < 0;
5459
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5460
+ return comparison <= 0;
5461
+ case "==" /* EQUAL */:
5462
+ return comparison === 0;
5463
+ case "!=" /* NOT_EQUAL */:
5464
+ return comparison !== 0;
5465
+ case ">" /* GREATER_THAN */:
5466
+ return comparison > 0;
5467
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5468
+ return comparison >= 0;
5469
+ default:
5470
+ return fail();
5590
5471
  }
5591
- return result;
5592
5472
  }
5593
- hasNext() {
5594
- return this.nodeStack.length > 0;
5473
+ isInequality() {
5474
+ return ([
5475
+ "<" /* LESS_THAN */,
5476
+ "<=" /* LESS_THAN_OR_EQUAL */,
5477
+ ">" /* GREATER_THAN */,
5478
+ ">=" /* GREATER_THAN_OR_EQUAL */,
5479
+ "!=" /* NOT_EQUAL */,
5480
+ "not-in" /* NOT_IN */
5481
+ ].indexOf(this.op) >= 0);
5595
5482
  }
5596
- peek() {
5597
- if (this.nodeStack.length === 0) {
5598
- return null;
5599
- }
5600
- const node = this.nodeStack[this.nodeStack.length - 1];
5601
- return { key: node.key, value: node.value };
5483
+ }
5484
+ function canonifyFilter(filter) {
5485
+ // TODO(b/29183165): Technically, this won't be unique if two values have
5486
+ // the same description, such as the int 3 and the string "3". So we should
5487
+ // add the types in here somehow, too.
5488
+ return (filter.field.canonicalString() +
5489
+ filter.op.toString() +
5490
+ canonicalId(filter.value));
5491
+ }
5492
+ function filterEquals(f1, f2) {
5493
+ return (f1.op === f2.op &&
5494
+ f1.field.isEqual(f2.field) &&
5495
+ valueEquals(f1.value, f2.value));
5496
+ }
5497
+ /** Returns a debug description for `filter`. */
5498
+ function stringifyFilter(filter) {
5499
+ return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
5500
+ }
5501
+ /** Filter that matches on key fields (i.e. '__name__'). */
5502
+ class KeyFieldFilter extends FieldFilter {
5503
+ constructor(field, op, value) {
5504
+ super(field, op, value);
5505
+ this.key = DocumentKey.fromName(value.referenceValue);
5602
5506
  }
5603
- } // end SortedMapIterator
5604
- // Represents a node in a Left-leaning Red-Black tree.
5605
- class LLRBNode {
5606
- constructor(key, value, color, left, right) {
5607
- this.key = key;
5608
- this.value = value;
5609
- this.color = color != null ? color : LLRBNode.RED;
5610
- this.left = left != null ? left : LLRBNode.EMPTY;
5611
- this.right = right != null ? right : LLRBNode.EMPTY;
5612
- this.size = this.left.size + 1 + this.right.size;
5507
+ matches(doc) {
5508
+ const comparison = DocumentKey.comparator(doc.key, this.key);
5509
+ return this.matchesComparison(comparison);
5613
5510
  }
5614
- // Returns a copy of the current node, optionally replacing pieces of it.
5615
- copy(key, value, color, left, right) {
5616
- return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
5511
+ }
5512
+ /** Filter that matches on key fields within an array. */
5513
+ class KeyFieldInFilter extends FieldFilter {
5514
+ constructor(field, value) {
5515
+ super(field, "in" /* IN */, value);
5516
+ this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
5617
5517
  }
5618
- isEmpty() {
5619
- return false;
5518
+ matches(doc) {
5519
+ return this.keys.some(key => key.isEqual(doc.key));
5620
5520
  }
5621
- // Traverses the tree in key order and calls the specified action function
5622
- // for each node. If action returns true, traversal is aborted.
5623
- // Returns the first truthy value returned by action, or the last falsey
5624
- // value returned by action.
5625
- inorderTraversal(action) {
5626
- return (this.left.inorderTraversal(action) ||
5627
- action(this.key, this.value) ||
5628
- this.right.inorderTraversal(action));
5521
+ }
5522
+ /** Filter that matches on key fields not present within an array. */
5523
+ class KeyFieldNotInFilter extends FieldFilter {
5524
+ constructor(field, value) {
5525
+ super(field, "not-in" /* NOT_IN */, value);
5526
+ this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
5629
5527
  }
5630
- // Traverses the tree in reverse key order and calls the specified action
5631
- // function for each node. If action returns true, traversal is aborted.
5632
- // Returns the first truthy value returned by action, or the last falsey
5633
- // value returned by action.
5634
- reverseTraversal(action) {
5635
- return (this.right.reverseTraversal(action) ||
5636
- action(this.key, this.value) ||
5637
- this.left.reverseTraversal(action));
5528
+ matches(doc) {
5529
+ return !this.keys.some(key => key.isEqual(doc.key));
5638
5530
  }
5639
- // Returns the minimum node in the tree.
5640
- min() {
5641
- if (this.left.isEmpty()) {
5642
- return this;
5643
- }
5644
- else {
5645
- return this.left.min();
5646
- }
5531
+ }
5532
+ function extractDocumentKeysFromArrayValue(op, value) {
5533
+ var _a;
5534
+ return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
5535
+ return DocumentKey.fromName(v.referenceValue);
5536
+ });
5537
+ }
5538
+ /** A Filter that implements the array-contains operator. */
5539
+ class ArrayContainsFilter extends FieldFilter {
5540
+ constructor(field, value) {
5541
+ super(field, "array-contains" /* ARRAY_CONTAINS */, value);
5647
5542
  }
5648
- // Returns the maximum key in the tree.
5649
- minKey() {
5650
- return this.min().key;
5543
+ matches(doc) {
5544
+ const other = doc.data.field(this.field);
5545
+ return isArray(other) && arrayValueContains(other.arrayValue, this.value);
5651
5546
  }
5652
- // Returns the maximum key in the tree.
5653
- maxKey() {
5654
- if (this.right.isEmpty()) {
5655
- return this.key;
5656
- }
5657
- else {
5658
- return this.right.maxKey();
5659
- }
5547
+ }
5548
+ /** A Filter that implements the IN operator. */
5549
+ class InFilter extends FieldFilter {
5550
+ constructor(field, value) {
5551
+ super(field, "in" /* IN */, value);
5660
5552
  }
5661
- // Returns new tree, with the key/value added.
5662
- insert(key, value, comparator) {
5663
- let n = this;
5664
- const cmp = comparator(key, n.key);
5665
- if (cmp < 0) {
5666
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
5667
- }
5668
- else if (cmp === 0) {
5669
- n = n.copy(null, value, null, null, null);
5670
- }
5671
- else {
5672
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
5673
- }
5674
- return n.fixUp();
5553
+ matches(doc) {
5554
+ const other = doc.data.field(this.field);
5555
+ return other !== null && arrayValueContains(this.value.arrayValue, other);
5675
5556
  }
5676
- removeMin() {
5677
- if (this.left.isEmpty()) {
5678
- return LLRBNode.EMPTY;
5679
- }
5680
- let n = this;
5681
- if (!n.left.isRed() && !n.left.left.isRed()) {
5682
- n = n.moveRedLeft();
5683
- }
5684
- n = n.copy(null, null, null, n.left.removeMin(), null);
5685
- return n.fixUp();
5557
+ }
5558
+ /** A Filter that implements the not-in operator. */
5559
+ class NotInFilter extends FieldFilter {
5560
+ constructor(field, value) {
5561
+ super(field, "not-in" /* NOT_IN */, value);
5686
5562
  }
5687
- // Returns new tree, with the specified item removed.
5688
- remove(key, comparator) {
5689
- let smallest;
5690
- let n = this;
5691
- if (comparator(key, n.key) < 0) {
5692
- if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
5693
- n = n.moveRedLeft();
5694
- }
5695
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
5563
+ matches(doc) {
5564
+ if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
5565
+ return false;
5696
5566
  }
5697
- else {
5698
- if (n.left.isRed()) {
5699
- n = n.rotateRight();
5700
- }
5701
- if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
5702
- n = n.moveRedRight();
5703
- }
5704
- if (comparator(key, n.key) === 0) {
5705
- if (n.right.isEmpty()) {
5706
- return LLRBNode.EMPTY;
5707
- }
5708
- else {
5709
- smallest = n.right.min();
5710
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
5711
- }
5712
- }
5713
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
5567
+ const other = doc.data.field(this.field);
5568
+ return other !== null && !arrayValueContains(this.value.arrayValue, other);
5569
+ }
5570
+ }
5571
+ /** A Filter that implements the array-contains-any operator. */
5572
+ class ArrayContainsAnyFilter extends FieldFilter {
5573
+ constructor(field, value) {
5574
+ super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
5575
+ }
5576
+ matches(doc) {
5577
+ const other = doc.data.field(this.field);
5578
+ if (!isArray(other) || !other.arrayValue.values) {
5579
+ return false;
5714
5580
  }
5715
- return n.fixUp();
5581
+ return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
5716
5582
  }
5717
- isRed() {
5718
- return this.color;
5583
+ }
5584
+ /**
5585
+ * Represents a bound of a query.
5586
+ *
5587
+ * The bound is specified with the given components representing a position and
5588
+ * whether it's just before or just after the position (relative to whatever the
5589
+ * query order is).
5590
+ *
5591
+ * The position represents a logical index position for a query. It's a prefix
5592
+ * of values for the (potentially implicit) order by clauses of a query.
5593
+ *
5594
+ * Bound provides a function to determine whether a document comes before or
5595
+ * after a bound. This is influenced by whether the position is just before or
5596
+ * just after the provided values.
5597
+ */
5598
+ class Bound {
5599
+ constructor(position, inclusive) {
5600
+ this.position = position;
5601
+ this.inclusive = inclusive;
5719
5602
  }
5720
- // Returns new tree after performing any needed rotations.
5721
- fixUp() {
5722
- let n = this;
5723
- if (n.right.isRed() && !n.left.isRed()) {
5724
- n = n.rotateLeft();
5603
+ }
5604
+ /**
5605
+ * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
5606
+ */
5607
+ class OrderBy {
5608
+ constructor(field, dir = "asc" /* ASCENDING */) {
5609
+ this.field = field;
5610
+ this.dir = dir;
5611
+ }
5612
+ }
5613
+ function canonifyOrderBy(orderBy) {
5614
+ // TODO(b/29183165): Make this collision robust.
5615
+ return orderBy.field.canonicalString() + orderBy.dir;
5616
+ }
5617
+ function stringifyOrderBy(orderBy) {
5618
+ return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
5619
+ }
5620
+ function orderByEquals(left, right) {
5621
+ return left.dir === right.dir && left.field.isEqual(right.field);
5622
+ }
5623
+ function boundCompareToDocument(bound, orderBy, doc) {
5624
+ let comparison = 0;
5625
+ for (let i = 0; i < bound.position.length; i++) {
5626
+ const orderByComponent = orderBy[i];
5627
+ const component = bound.position[i];
5628
+ if (orderByComponent.field.isKeyField()) {
5629
+ comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
5725
5630
  }
5726
- if (n.left.isRed() && n.left.left.isRed()) {
5727
- n = n.rotateRight();
5631
+ else {
5632
+ const docValue = doc.data.field(orderByComponent.field);
5633
+ comparison = valueCompare(component, docValue);
5728
5634
  }
5729
- if (n.left.isRed() && n.right.isRed()) {
5730
- n = n.colorFlip();
5635
+ if (orderByComponent.dir === "desc" /* DESCENDING */) {
5636
+ comparison = comparison * -1;
5731
5637
  }
5732
- return n;
5733
- }
5734
- moveRedLeft() {
5735
- let n = this.colorFlip();
5736
- if (n.right.left.isRed()) {
5737
- n = n.copy(null, null, null, null, n.right.rotateRight());
5738
- n = n.rotateLeft();
5739
- n = n.colorFlip();
5638
+ if (comparison !== 0) {
5639
+ break;
5740
5640
  }
5741
- return n;
5742
5641
  }
5743
- moveRedRight() {
5744
- let n = this.colorFlip();
5745
- if (n.left.left.isRed()) {
5746
- n = n.rotateRight();
5747
- n = n.colorFlip();
5748
- }
5749
- return n;
5642
+ return comparison;
5643
+ }
5644
+ /**
5645
+ * Returns true if a document sorts after a bound using the provided sort
5646
+ * order.
5647
+ */
5648
+ function boundSortsAfterDocument(bound, orderBy, doc) {
5649
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5650
+ return bound.inclusive ? comparison >= 0 : comparison > 0;
5651
+ }
5652
+ /**
5653
+ * Returns true if a document sorts before a bound using the provided sort
5654
+ * order.
5655
+ */
5656
+ function boundSortsBeforeDocument(bound, orderBy, doc) {
5657
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5658
+ return bound.inclusive ? comparison <= 0 : comparison < 0;
5659
+ }
5660
+ function boundEquals(left, right) {
5661
+ if (left === null) {
5662
+ return right === null;
5750
5663
  }
5751
- rotateLeft() {
5752
- const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
5753
- return this.right.copy(null, null, this.color, nl, null);
5664
+ else if (right === null) {
5665
+ return false;
5754
5666
  }
5755
- rotateRight() {
5756
- const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
5757
- return this.left.copy(null, null, this.color, null, nr);
5667
+ if (left.inclusive !== right.inclusive ||
5668
+ left.position.length !== right.position.length) {
5669
+ return false;
5758
5670
  }
5759
- colorFlip() {
5760
- const left = this.left.copy(null, null, !this.left.color, null, null);
5761
- const right = this.right.copy(null, null, !this.right.color, null, null);
5762
- return this.copy(null, null, !this.color, left, right);
5671
+ for (let i = 0; i < left.position.length; i++) {
5672
+ const leftPosition = left.position[i];
5673
+ const rightPosition = right.position[i];
5674
+ if (!valueEquals(leftPosition, rightPosition)) {
5675
+ return false;
5676
+ }
5763
5677
  }
5764
- // For testing.
5765
- checkMaxDepth() {
5766
- const blackDepth = this.check();
5767
- if (Math.pow(2.0, blackDepth) <= this.size + 1) {
5768
- return true;
5678
+ return true;
5679
+ }
5680
+
5681
+ /**
5682
+ * @license
5683
+ * Copyright 2017 Google LLC
5684
+ *
5685
+ * Licensed under the Apache License, Version 2.0 (the "License");
5686
+ * you may not use this file except in compliance with the License.
5687
+ * You may obtain a copy of the License at
5688
+ *
5689
+ * http://www.apache.org/licenses/LICENSE-2.0
5690
+ *
5691
+ * Unless required by applicable law or agreed to in writing, software
5692
+ * distributed under the License is distributed on an "AS IS" BASIS,
5693
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5694
+ * See the License for the specific language governing permissions and
5695
+ * limitations under the License.
5696
+ */
5697
+ /**
5698
+ * Query encapsulates all the query attributes we support in the SDK. It can
5699
+ * be run against the LocalStore, as well as be converted to a `Target` to
5700
+ * query the RemoteStore results.
5701
+ *
5702
+ * Visible for testing.
5703
+ */
5704
+ class QueryImpl {
5705
+ /**
5706
+ * Initializes a Query with a path and optional additional query constraints.
5707
+ * Path must currently be empty if this is a collection group query.
5708
+ */
5709
+ constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
5710
+ this.path = path;
5711
+ this.collectionGroup = collectionGroup;
5712
+ this.explicitOrderBy = explicitOrderBy;
5713
+ this.filters = filters;
5714
+ this.limit = limit;
5715
+ this.limitType = limitType;
5716
+ this.startAt = startAt;
5717
+ this.endAt = endAt;
5718
+ this.memoizedOrderBy = null;
5719
+ // The corresponding `Target` of this `Query` instance.
5720
+ this.memoizedTarget = null;
5721
+ if (this.startAt) ;
5722
+ if (this.endAt) ;
5723
+ }
5724
+ }
5725
+ /** Creates a new Query instance with the options provided. */
5726
+ function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
5727
+ return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
5728
+ }
5729
+ /** Creates a new Query for a query that matches all documents at `path` */
5730
+ function newQueryForPath(path) {
5731
+ return new QueryImpl(path);
5732
+ }
5733
+ /**
5734
+ * Helper to convert a collection group query into a collection query at a
5735
+ * specific path. This is used when executing collection group queries, since
5736
+ * we have to split the query into a set of collection queries at multiple
5737
+ * paths.
5738
+ */
5739
+ function asCollectionQueryAtPath(query, path) {
5740
+ return new QueryImpl(path,
5741
+ /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5742
+ }
5743
+ /**
5744
+ * Returns true if this query does not specify any query constraints that
5745
+ * could remove results.
5746
+ */
5747
+ function queryMatchesAllDocuments(query) {
5748
+ return (query.filters.length === 0 &&
5749
+ query.limit === null &&
5750
+ query.startAt == null &&
5751
+ query.endAt == null &&
5752
+ (query.explicitOrderBy.length === 0 ||
5753
+ (query.explicitOrderBy.length === 1 &&
5754
+ query.explicitOrderBy[0].field.isKeyField())));
5755
+ }
5756
+ function getFirstOrderByField(query) {
5757
+ return query.explicitOrderBy.length > 0
5758
+ ? query.explicitOrderBy[0].field
5759
+ : null;
5760
+ }
5761
+ function getInequalityFilterField(query) {
5762
+ for (const filter of query.filters) {
5763
+ if (filter.isInequality()) {
5764
+ return filter.field;
5769
5765
  }
5770
- else {
5771
- return false;
5766
+ }
5767
+ return null;
5768
+ }
5769
+ /**
5770
+ * Checks if any of the provided Operators are included in the query and
5771
+ * returns the first one that is, or null if none are.
5772
+ */
5773
+ function findFilterOperator(query, operators) {
5774
+ for (const filter of query.filters) {
5775
+ if (operators.indexOf(filter.op) >= 0) {
5776
+ return filter.op;
5772
5777
  }
5773
5778
  }
5774
- // In a balanced RB tree, the black-depth (number of black nodes) from root to
5775
- // leaves is equal on both sides. This function verifies that or asserts.
5776
- check() {
5777
- if (this.isRed() && this.left.isRed()) {
5778
- throw fail();
5779
+ return null;
5780
+ }
5781
+ /**
5782
+ * Creates a new Query for a collection group query that matches all documents
5783
+ * within the provided collection group.
5784
+ */
5785
+ function newQueryForCollectionGroup(collectionId) {
5786
+ return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5787
+ }
5788
+ /**
5789
+ * Returns whether the query matches a single document by path (rather than a
5790
+ * collection).
5791
+ */
5792
+ function isDocumentQuery$1(query) {
5793
+ return (DocumentKey.isDocumentKey(query.path) &&
5794
+ query.collectionGroup === null &&
5795
+ query.filters.length === 0);
5796
+ }
5797
+ /**
5798
+ * Returns whether the query matches a collection group rather than a specific
5799
+ * collection.
5800
+ */
5801
+ function isCollectionGroupQuery(query) {
5802
+ return query.collectionGroup !== null;
5803
+ }
5804
+ /**
5805
+ * Returns the implicit order by constraint that is used to execute the Query,
5806
+ * which can be different from the order by constraints the user provided (e.g.
5807
+ * the SDK and backend always orders by `__name__`).
5808
+ */
5809
+ function queryOrderBy(query) {
5810
+ const queryImpl = debugCast(query);
5811
+ if (queryImpl.memoizedOrderBy === null) {
5812
+ queryImpl.memoizedOrderBy = [];
5813
+ const inequalityField = getInequalityFilterField(queryImpl);
5814
+ const firstOrderByField = getFirstOrderByField(queryImpl);
5815
+ if (inequalityField !== null && firstOrderByField === null) {
5816
+ // In order to implicitly add key ordering, we must also add the
5817
+ // inequality filter field for it to be a valid query.
5818
+ // Note that the default inequality field and key ordering is ascending.
5819
+ if (!inequalityField.isKeyField()) {
5820
+ queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5821
+ }
5822
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
5779
5823
  }
5780
- if (this.right.isRed()) {
5781
- throw fail();
5824
+ else {
5825
+ let foundKeyOrdering = false;
5826
+ for (const orderBy of queryImpl.explicitOrderBy) {
5827
+ queryImpl.memoizedOrderBy.push(orderBy);
5828
+ if (orderBy.field.isKeyField()) {
5829
+ foundKeyOrdering = true;
5830
+ }
5831
+ }
5832
+ if (!foundKeyOrdering) {
5833
+ // The order of the implicit key ordering always matches the last
5834
+ // explicit order by
5835
+ const lastDirection = queryImpl.explicitOrderBy.length > 0
5836
+ ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5837
+ .dir
5838
+ : "asc" /* ASCENDING */;
5839
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
5840
+ }
5782
5841
  }
5783
- const blackDepth = this.left.check();
5784
- if (blackDepth !== this.right.check()) {
5785
- throw fail();
5842
+ }
5843
+ return queryImpl.memoizedOrderBy;
5844
+ }
5845
+ /**
5846
+ * Converts this `Query` instance to it's corresponding `Target` representation.
5847
+ */
5848
+ function queryToTarget(query) {
5849
+ const queryImpl = debugCast(query);
5850
+ if (!queryImpl.memoizedTarget) {
5851
+ if (queryImpl.limitType === "F" /* First */) {
5852
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
5786
5853
  }
5787
5854
  else {
5788
- return blackDepth + (this.isRed() ? 0 : 1);
5855
+ // Flip the orderBy directions since we want the last results
5856
+ const orderBys = [];
5857
+ for (const orderBy of queryOrderBy(queryImpl)) {
5858
+ const dir = orderBy.dir === "desc" /* DESCENDING */
5859
+ ? "asc" /* ASCENDING */
5860
+ : "desc" /* DESCENDING */;
5861
+ orderBys.push(new OrderBy(orderBy.field, dir));
5862
+ }
5863
+ // We need to swap the cursors to match the now-flipped query ordering.
5864
+ const startAt = queryImpl.endAt
5865
+ ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)
5866
+ : null;
5867
+ const endAt = queryImpl.startAt
5868
+ ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)
5869
+ : null;
5870
+ // Now return as a LimitType.First query.
5871
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5789
5872
  }
5790
5873
  }
5791
- } // end LLRBNode
5792
- // Empty node is shared between all LLRB trees.
5793
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5794
- LLRBNode.EMPTY = null;
5795
- LLRBNode.RED = true;
5796
- LLRBNode.BLACK = false;
5797
- // Represents an empty node (a leaf node in the Red-Black Tree).
5798
- class LLRBEmptyNode {
5799
- constructor() {
5800
- this.size = 0;
5801
- }
5802
- get key() {
5803
- throw fail();
5804
- }
5805
- get value() {
5806
- throw fail();
5807
- }
5808
- get color() {
5809
- throw fail();
5810
- }
5811
- get left() {
5812
- throw fail();
5813
- }
5814
- get right() {
5815
- throw fail();
5816
- }
5817
- // Returns a copy of the current node.
5818
- copy(key, value, color, left, right) {
5819
- return this;
5874
+ return queryImpl.memoizedTarget;
5875
+ }
5876
+ function queryWithAddedFilter(query, filter) {
5877
+ const newFilters = query.filters.concat([filter]);
5878
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5879
+ }
5880
+ function queryWithAddedOrderBy(query, orderBy) {
5881
+ // TODO(dimond): validate that orderBy does not list the same key twice.
5882
+ const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5883
+ return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5884
+ }
5885
+ function queryWithLimit(query, limit, limitType) {
5886
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5887
+ }
5888
+ function queryWithStartAt(query, bound) {
5889
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5890
+ }
5891
+ function queryWithEndAt(query, bound) {
5892
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5893
+ }
5894
+ function queryEquals(left, right) {
5895
+ return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5896
+ left.limitType === right.limitType);
5897
+ }
5898
+ // TODO(b/29183165): This is used to get a unique string from a query to, for
5899
+ // example, use as a dictionary key, but the implementation is subject to
5900
+ // collisions. Make it collision-free.
5901
+ function canonifyQuery(query) {
5902
+ return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5903
+ }
5904
+ function stringifyQuery(query) {
5905
+ return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5906
+ }
5907
+ /** Returns whether `doc` matches the constraints of `query`. */
5908
+ function queryMatches(query, doc) {
5909
+ return (doc.isFoundDocument() &&
5910
+ queryMatchesPathAndCollectionGroup(query, doc) &&
5911
+ queryMatchesOrderBy(query, doc) &&
5912
+ queryMatchesFilters(query, doc) &&
5913
+ queryMatchesBounds(query, doc));
5914
+ }
5915
+ function queryMatchesPathAndCollectionGroup(query, doc) {
5916
+ const docPath = doc.key.path;
5917
+ if (query.collectionGroup !== null) {
5918
+ // NOTE: this.path is currently always empty since we don't expose Collection
5919
+ // Group queries rooted at a document path yet.
5920
+ return (doc.key.hasCollectionId(query.collectionGroup) &&
5921
+ query.path.isPrefixOf(docPath));
5820
5922
  }
5821
- // Returns a copy of the tree, with the specified key/value added.
5822
- insert(key, value, comparator) {
5823
- return new LLRBNode(key, value);
5923
+ else if (DocumentKey.isDocumentKey(query.path)) {
5924
+ // exact match for document queries
5925
+ return query.path.isEqual(docPath);
5824
5926
  }
5825
- // Returns a copy of the tree, with the specified key removed.
5826
- remove(key, comparator) {
5827
- return this;
5927
+ else {
5928
+ // shallow ancestor queries by default
5929
+ return query.path.isImmediateParentOf(docPath);
5828
5930
  }
5829
- isEmpty() {
5830
- return true;
5931
+ }
5932
+ /**
5933
+ * A document must have a value for every ordering clause in order to show up
5934
+ * in the results.
5935
+ */
5936
+ function queryMatchesOrderBy(query, doc) {
5937
+ for (const orderBy of query.explicitOrderBy) {
5938
+ // order by key always matches
5939
+ if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5940
+ return false;
5941
+ }
5831
5942
  }
5832
- inorderTraversal(action) {
5833
- return false;
5943
+ return true;
5944
+ }
5945
+ function queryMatchesFilters(query, doc) {
5946
+ for (const filter of query.filters) {
5947
+ if (!filter.matches(doc)) {
5948
+ return false;
5949
+ }
5834
5950
  }
5835
- reverseTraversal(action) {
5951
+ return true;
5952
+ }
5953
+ /** Makes sure a document is within the bounds, if provided. */
5954
+ function queryMatchesBounds(query, doc) {
5955
+ if (query.startAt &&
5956
+ !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5836
5957
  return false;
5837
5958
  }
5838
- minKey() {
5839
- return null;
5840
- }
5841
- maxKey() {
5842
- return null;
5843
- }
5844
- isRed() {
5959
+ if (query.endAt &&
5960
+ !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5845
5961
  return false;
5846
5962
  }
5847
- // For testing.
5848
- checkMaxDepth() {
5849
- return true;
5850
- }
5851
- check() {
5963
+ return true;
5964
+ }
5965
+ /**
5966
+ * Returns the collection group that this query targets.
5967
+ *
5968
+ * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5969
+ * synchronization for query results.
5970
+ */
5971
+ function queryCollectionGroup(query) {
5972
+ return (query.collectionGroup ||
5973
+ (query.path.length % 2 === 1
5974
+ ? query.path.lastSegment()
5975
+ : query.path.get(query.path.length - 2)));
5976
+ }
5977
+ /**
5978
+ * Returns a new comparator function that can be used to compare two documents
5979
+ * based on the Query's ordering constraint.
5980
+ */
5981
+ function newQueryComparator(query) {
5982
+ return (d1, d2) => {
5983
+ let comparedOnKeyField = false;
5984
+ for (const orderBy of queryOrderBy(query)) {
5985
+ const comp = compareDocs(orderBy, d1, d2);
5986
+ if (comp !== 0) {
5987
+ return comp;
5988
+ }
5989
+ comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
5990
+ }
5852
5991
  return 0;
5992
+ };
5993
+ }
5994
+ function compareDocs(orderBy, d1, d2) {
5995
+ const comparison = orderBy.field.isKeyField()
5996
+ ? DocumentKey.comparator(d1.key, d2.key)
5997
+ : compareDocumentsByField(orderBy.field, d1, d2);
5998
+ switch (orderBy.dir) {
5999
+ case "asc" /* ASCENDING */:
6000
+ return comparison;
6001
+ case "desc" /* DESCENDING */:
6002
+ return -1 * comparison;
6003
+ default:
6004
+ return fail();
5853
6005
  }
5854
- } // end LLRBEmptyNode
5855
- LLRBNode.EMPTY = new LLRBEmptyNode();
6006
+ }
5856
6007
 
5857
6008
  /**
5858
6009
  * @license
@@ -5871,218 +6022,97 @@ LLRBNode.EMPTY = new LLRBEmptyNode();
5871
6022
  * limitations under the License.
5872
6023
  */
5873
6024
  /**
5874
- * SortedSet is an immutable (copy-on-write) collection that holds elements
5875
- * in order specified by the provided comparator.
5876
- *
5877
- * NOTE: if provided comparator returns 0 for two elements, we consider them to
5878
- * be equal!
6025
+ * A map implementation that uses objects as keys. Objects must have an
6026
+ * associated equals function and must be immutable. Entries in the map are
6027
+ * stored together with the key being produced from the mapKeyFn. This map
6028
+ * automatically handles collisions of keys.
5879
6029
  */
5880
- class SortedSet {
5881
- constructor(comparator) {
5882
- this.comparator = comparator;
5883
- this.data = new SortedMap(this.comparator);
5884
- }
5885
- has(elem) {
5886
- return this.data.get(elem) !== null;
5887
- }
5888
- first() {
5889
- return this.data.minKey();
5890
- }
5891
- last() {
5892
- return this.data.maxKey();
5893
- }
5894
- get size() {
5895
- return this.data.size;
5896
- }
5897
- indexOf(elem) {
5898
- return this.data.indexOf(elem);
5899
- }
5900
- /** Iterates elements in order defined by "comparator" */
5901
- forEach(cb) {
5902
- this.data.inorderTraversal((k, v) => {
5903
- cb(k);
5904
- return false;
5905
- });
5906
- }
5907
- /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
5908
- forEachInRange(range, cb) {
5909
- const iter = this.data.getIteratorFrom(range[0]);
5910
- while (iter.hasNext()) {
5911
- const elem = iter.getNext();
5912
- if (this.comparator(elem.key, range[1]) >= 0) {
5913
- return;
5914
- }
5915
- cb(elem.key);
5916
- }
6030
+ class ObjectMap {
6031
+ constructor(mapKeyFn, equalsFn) {
6032
+ this.mapKeyFn = mapKeyFn;
6033
+ this.equalsFn = equalsFn;
6034
+ /**
6035
+ * The inner map for a key/value pair. Due to the possibility of collisions we
6036
+ * keep a list of entries that we do a linear search through to find an actual
6037
+ * match. Note that collisions should be rare, so we still expect near
6038
+ * constant time lookups in practice.
6039
+ */
6040
+ this.inner = {};
6041
+ /** The number of entries stored in the map */
6042
+ this.innerSize = 0;
5917
6043
  }
5918
- /**
5919
- * Iterates over `elem`s such that: start &lt;= elem until false is returned.
5920
- */
5921
- forEachWhile(cb, start) {
5922
- let iter;
5923
- if (start !== undefined) {
5924
- iter = this.data.getIteratorFrom(start);
5925
- }
5926
- else {
5927
- iter = this.data.getIterator();
6044
+ /** Get a value for this key, or undefined if it does not exist. */
6045
+ get(key) {
6046
+ const id = this.mapKeyFn(key);
6047
+ const matches = this.inner[id];
6048
+ if (matches === undefined) {
6049
+ return undefined;
5928
6050
  }
5929
- while (iter.hasNext()) {
5930
- const elem = iter.getNext();
5931
- const result = cb(elem.key);
5932
- if (!result) {
5933
- return;
6051
+ for (const [otherKey, value] of matches) {
6052
+ if (this.equalsFn(otherKey, key)) {
6053
+ return value;
5934
6054
  }
5935
6055
  }
6056
+ return undefined;
5936
6057
  }
5937
- /** Finds the least element greater than or equal to `elem`. */
5938
- firstAfterOrEqual(elem) {
5939
- const iter = this.data.getIteratorFrom(elem);
5940
- return iter.hasNext() ? iter.getNext().key : null;
5941
- }
5942
- getIterator() {
5943
- return new SortedSetIterator(this.data.getIterator());
5944
- }
5945
- getIteratorFrom(key) {
5946
- return new SortedSetIterator(this.data.getIteratorFrom(key));
5947
- }
5948
- /** Inserts or updates an element */
5949
- add(elem) {
5950
- return this.copy(this.data.remove(elem).insert(elem, true));
6058
+ has(key) {
6059
+ return this.get(key) !== undefined;
5951
6060
  }
5952
- /** Deletes an element */
5953
- delete(elem) {
5954
- if (!this.has(elem)) {
5955
- return this;
6061
+ /** Put this key and value in the map. */
6062
+ set(key, value) {
6063
+ const id = this.mapKeyFn(key);
6064
+ const matches = this.inner[id];
6065
+ if (matches === undefined) {
6066
+ this.inner[id] = [[key, value]];
6067
+ this.innerSize++;
6068
+ return;
5956
6069
  }
5957
- return this.copy(this.data.remove(elem));
5958
- }
5959
- isEmpty() {
5960
- return this.data.isEmpty();
5961
- }
5962
- unionWith(other) {
5963
- let result = this;
5964
- // Make sure `result` always refers to the larger one of the two sets.
5965
- if (result.size < other.size) {
5966
- result = other;
5967
- other = this;
6070
+ for (let i = 0; i < matches.length; i++) {
6071
+ if (this.equalsFn(matches[i][0], key)) {
6072
+ // This is updating an existing entry and does not increase `innerSize`.
6073
+ matches[i] = [key, value];
6074
+ return;
6075
+ }
5968
6076
  }
5969
- other.forEach(elem => {
5970
- result = result.add(elem);
5971
- });
5972
- return result;
6077
+ matches.push([key, value]);
6078
+ this.innerSize++;
5973
6079
  }
5974
- isEqual(other) {
5975
- if (!(other instanceof SortedSet)) {
5976
- return false;
5977
- }
5978
- if (this.size !== other.size) {
6080
+ /**
6081
+ * Remove this key from the map. Returns a boolean if anything was deleted.
6082
+ */
6083
+ delete(key) {
6084
+ const id = this.mapKeyFn(key);
6085
+ const matches = this.inner[id];
6086
+ if (matches === undefined) {
5979
6087
  return false;
5980
6088
  }
5981
- const thisIt = this.data.getIterator();
5982
- const otherIt = other.data.getIterator();
5983
- while (thisIt.hasNext()) {
5984
- const thisElem = thisIt.getNext().key;
5985
- const otherElem = otherIt.getNext().key;
5986
- if (this.comparator(thisElem, otherElem) !== 0) {
5987
- return false;
6089
+ for (let i = 0; i < matches.length; i++) {
6090
+ if (this.equalsFn(matches[i][0], key)) {
6091
+ if (matches.length === 1) {
6092
+ delete this.inner[id];
6093
+ }
6094
+ else {
6095
+ matches.splice(i, 1);
6096
+ }
6097
+ this.innerSize--;
6098
+ return true;
5988
6099
  }
5989
6100
  }
5990
- return true;
6101
+ return false;
5991
6102
  }
5992
- toArray() {
5993
- const res = [];
5994
- this.forEach(targetId => {
5995
- res.push(targetId);
6103
+ forEach(fn) {
6104
+ forEach(this.inner, (_, entries) => {
6105
+ for (const [k, v] of entries) {
6106
+ fn(k, v);
6107
+ }
5996
6108
  });
5997
- return res;
5998
- }
5999
- toString() {
6000
- const result = [];
6001
- this.forEach(elem => result.push(elem));
6002
- return 'SortedSet(' + result.toString() + ')';
6003
- }
6004
- copy(data) {
6005
- const result = new SortedSet(this.comparator);
6006
- result.data = data;
6007
- return result;
6008
- }
6009
- }
6010
- class SortedSetIterator {
6011
- constructor(iter) {
6012
- this.iter = iter;
6013
- }
6014
- getNext() {
6015
- return this.iter.getNext().key;
6016
6109
  }
6017
- hasNext() {
6018
- return this.iter.hasNext();
6110
+ isEmpty() {
6111
+ return isEmpty(this.inner);
6019
6112
  }
6020
- }
6021
- /**
6022
- * Compares two sorted sets for equality using their natural ordering. The
6023
- * method computes the intersection and invokes `onAdd` for every element that
6024
- * is in `after` but not `before`. `onRemove` is invoked for every element in
6025
- * `before` but missing from `after`.
6026
- *
6027
- * The method creates a copy of both `before` and `after` and runs in O(n log
6028
- * n), where n is the size of the two lists.
6029
- *
6030
- * @param before - The elements that exist in the original set.
6031
- * @param after - The elements to diff against the original set.
6032
- * @param comparator - The comparator for the elements in before and after.
6033
- * @param onAdd - A function to invoke for every element that is part of `
6034
- * after` but not `before`.
6035
- * @param onRemove - A function to invoke for every element that is part of
6036
- * `before` but not `after`.
6037
- */
6038
- function diffSortedSets(before, after, comparator, onAdd, onRemove) {
6039
- const beforeIt = before.getIterator();
6040
- const afterIt = after.getIterator();
6041
- let beforeValue = advanceIterator(beforeIt);
6042
- let afterValue = advanceIterator(afterIt);
6043
- // Walk through the two sets at the same time, using the ordering defined by
6044
- // `comparator`.
6045
- while (beforeValue || afterValue) {
6046
- let added = false;
6047
- let removed = false;
6048
- if (beforeValue && afterValue) {
6049
- const cmp = comparator(beforeValue, afterValue);
6050
- if (cmp < 0) {
6051
- // The element was removed if the next element in our ordered
6052
- // walkthrough is only in `before`.
6053
- removed = true;
6054
- }
6055
- else if (cmp > 0) {
6056
- // The element was added if the next element in our ordered walkthrough
6057
- // is only in `after`.
6058
- added = true;
6059
- }
6060
- }
6061
- else if (beforeValue != null) {
6062
- removed = true;
6063
- }
6064
- else {
6065
- added = true;
6066
- }
6067
- if (added) {
6068
- onAdd(afterValue);
6069
- afterValue = advanceIterator(afterIt);
6070
- }
6071
- else if (removed) {
6072
- onRemove(beforeValue);
6073
- beforeValue = advanceIterator(beforeIt);
6074
- }
6075
- else {
6076
- beforeValue = advanceIterator(beforeIt);
6077
- afterValue = advanceIterator(afterIt);
6078
- }
6113
+ size() {
6114
+ return this.innerSize;
6079
6115
  }
6080
- }
6081
- /**
6082
- * Returns the next element from the iterator or `undefined` if none available.
6083
- */
6084
- function advanceIterator(it) {
6085
- return it.hasNext() ? it.getNext() : undefined;
6086
6116
  }
6087
6117
 
6088
6118
  /**
@@ -6106,8 +6136,12 @@ function mutableDocumentMap() {
6106
6136
  return EMPTY_MUTABLE_DOCUMENT_MAP;
6107
6137
  }
6108
6138
  const EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);
6109
- function documentMap() {
6110
- return EMPTY_DOCUMENT_MAP;
6139
+ function documentMap(...docs) {
6140
+ let map = EMPTY_DOCUMENT_MAP;
6141
+ for (const doc of docs) {
6142
+ map = map.insert(doc.key, doc);
6143
+ }
6144
+ return map;
6111
6145
  }
6112
6146
  function newOverlayMap() {
6113
6147
  return new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r));
@@ -10000,9 +10034,9 @@ class MemoryIndexManager {
10000
10034
  // Field indices are not supported with memory persistence.
10001
10035
  return PersistencePromise.resolve(null);
10002
10036
  }
10003
- getFieldIndex(transaction, target) {
10037
+ getIndexType(transaction, target) {
10004
10038
  // Field indices are not supported with memory persistence.
10005
- return PersistencePromise.resolve(null);
10039
+ return PersistencePromise.resolve(0 /* NONE */);
10006
10040
  }
10007
10041
  getFieldIndexes(transaction, collectionGroup) {
10008
10042
  // Field indices are not supported with memory persistence.
@@ -10012,6 +10046,9 @@ class MemoryIndexManager {
10012
10046
  // Field indices are not supported with memory persistence.
10013
10047
  return PersistencePromise.resolve(null);
10014
10048
  }
10049
+ getMinOffset(transaction, target) {
10050
+ return PersistencePromise.resolve(IndexOffset.min());
10051
+ }
10015
10052
  updateCollectionGroup(transaction, collectionGroup, offset) {
10016
10053
  // Field indices are not supported with memory persistence.
10017
10054
  return PersistencePromise.resolve();
@@ -10187,7 +10224,7 @@ class IndexedDbIndexManager {
10187
10224
  const lowerBoundEncoded = this.encodeBound(index, subTarget, lowerBound);
10188
10225
  const upperBoundEncoded = this.encodeBound(index, subTarget, upperBound);
10189
10226
  const notInEncoded = this.encodeValues(index, subTarget, notInValues);
10190
- const indexRanges = this.generateIndexRanges(index.indexId, arrayValues, lowerBoundEncoded, !!lowerBound && lowerBound.inclusive, upperBoundEncoded, !!upperBound && upperBound.inclusive, notInEncoded);
10227
+ const indexRanges = this.generateIndexRanges(index.indexId, arrayValues, lowerBoundEncoded, lowerBound.inclusive, upperBoundEncoded, upperBound.inclusive, notInEncoded);
10191
10228
  return PersistencePromise.forEach(indexRanges, (indexRange) => {
10192
10229
  return indexEntries
10193
10230
  .loadFirst(indexRange, target.limit)
@@ -10225,22 +10262,18 @@ class IndexedDbIndexManager {
10225
10262
  // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
10226
10263
  // combined with the values from the query bounds.
10227
10264
  const totalScans = (arrayValues != null ? arrayValues.length : 1) *
10228
- Math.max(lowerBounds != null ? lowerBounds.length : 1, upperBounds != null ? upperBounds.length : 1);
10265
+ Math.max(lowerBounds.length, upperBounds.length);
10229
10266
  const scansPerArrayElement = totalScans / (arrayValues != null ? arrayValues.length : 1);
10230
10267
  const indexRanges = [];
10231
10268
  for (let i = 0; i < totalScans; ++i) {
10232
10269
  const arrayValue = arrayValues
10233
10270
  ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])
10234
10271
  : EMPTY_VALUE;
10235
- const lowerBound = lowerBounds
10236
- ? this.generateLowerBound(indexId, arrayValue, lowerBounds[i % scansPerArrayElement], lowerBoundInclusive)
10237
- : this.generateEmptyBound(indexId);
10238
- const upperBound = upperBounds
10239
- ? this.generateUpperBound(indexId, arrayValue, upperBounds[i % scansPerArrayElement], upperBoundInclusive)
10240
- : this.generateEmptyBound(indexId + 1);
10241
- indexRanges.push(...this.createRange(lowerBound, upperBound, notInValues.map((notIn // make non-nullable
10242
- ) => this.generateLowerBound(indexId, arrayValue, notIn,
10243
- /* inclusive= */ true))));
10272
+ const lowerBound = this.generateLowerBound(indexId, arrayValue, lowerBounds[i % scansPerArrayElement], lowerBoundInclusive);
10273
+ const upperBound = this.generateUpperBound(indexId, arrayValue, upperBounds[i % scansPerArrayElement], upperBoundInclusive);
10274
+ const notInBound = notInValues.map(notIn => this.generateLowerBound(indexId, arrayValue, notIn,
10275
+ /* inclusive= */ true));
10276
+ indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));
10244
10277
  }
10245
10278
  return indexRanges;
10246
10279
  }
@@ -10254,25 +10287,38 @@ class IndexedDbIndexManager {
10254
10287
  const entry = new IndexEntry(indexId, DocumentKey.empty(), arrayValue, directionalValue);
10255
10288
  return inclusive ? entry.successor() : entry;
10256
10289
  }
10257
- /**
10258
- * Generates an empty bound that scopes the index scan to the current index
10259
- * and user.
10260
- */
10261
- generateEmptyBound(indexId) {
10262
- return new IndexEntry(indexId, DocumentKey.empty(), EMPTY_VALUE, EMPTY_VALUE);
10263
- }
10264
10290
  getFieldIndex(transaction, target) {
10265
10291
  const targetIndexMatcher = new TargetIndexMatcher(target);
10266
10292
  const collectionGroup = target.collectionGroup != null
10267
10293
  ? target.collectionGroup
10268
10294
  : target.path.lastSegment();
10269
10295
  return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {
10270
- const matchingIndexes = indexes.filter(i => targetIndexMatcher.servedByIndex(i));
10271
- // Return the index that matches the most number of segments.
10272
- matchingIndexes.sort((l, r) => r.fields.length - l.fields.length);
10273
- return matchingIndexes.length > 0 ? matchingIndexes[0] : null;
10296
+ // Return the index with the most number of segments.
10297
+ let index = null;
10298
+ for (const candidate of indexes) {
10299
+ const matches = targetIndexMatcher.servedByIndex(candidate);
10300
+ if (matches &&
10301
+ (!index || candidate.fields.length > index.fields.length)) {
10302
+ index = candidate;
10303
+ }
10304
+ }
10305
+ return index;
10274
10306
  });
10275
10307
  }
10308
+ getIndexType(transaction, target) {
10309
+ let indexType = 2 /* FULL */;
10310
+ return PersistencePromise.forEach(this.getSubTargets(target), (target) => {
10311
+ return this.getFieldIndex(transaction, target).next(index => {
10312
+ if (!index) {
10313
+ indexType = 0 /* NONE */;
10314
+ }
10315
+ else if (indexType !== 0 /* NONE */ &&
10316
+ index.fields.length < targetGetSegmentCount(target)) {
10317
+ indexType = 1 /* PARTIAL */;
10318
+ }
10319
+ });
10320
+ }).next(() => indexType);
10321
+ }
10276
10322
  /**
10277
10323
  * Returns the byte encoded form of the directional values in the field index.
10278
10324
  * Returns `null` if the document does not have all fields specified in the
@@ -10335,9 +10381,6 @@ class IndexedDbIndexManager {
10335
10381
  * queries, a list of possible values is returned.
10336
10382
  */
10337
10383
  encodeBound(fieldIndex, target, bound) {
10338
- if (bound == null) {
10339
- return null;
10340
- }
10341
10384
  return this.encodeValues(fieldIndex, target, bound.position);
10342
10385
  }
10343
10386
  /** Returns the byte representation for the provided encoders. */
@@ -10532,7 +10575,7 @@ class IndexedDbIndexManager {
10532
10575
  * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
10533
10576
  */
10534
10577
  createRange(lower, upper, notInValues) {
10535
- // The notIb values need to be sorted and unique so that we can return a
10578
+ // The notIn values need to be sorted and unique so that we can return a
10536
10579
  // sorted set of non-overlapping ranges.
10537
10580
  notInValues = notInValues
10538
10581
  .sort((l, r) => indexEntryComparator(l, r))
@@ -10578,6 +10621,20 @@ class IndexedDbIndexManager {
10578
10621
  }
10579
10622
  return ranges;
10580
10623
  }
10624
+ getMinOffset(transaction, target) {
10625
+ let offset;
10626
+ return PersistencePromise.forEach(this.getSubTargets(target), (target) => {
10627
+ return this.getFieldIndex(transaction, target).next(index => {
10628
+ if (!index) {
10629
+ offset = IndexOffset.min();
10630
+ }
10631
+ else if (!offset ||
10632
+ indexOffsetComparator(index.indexState.offset, offset) < 0) {
10633
+ offset = index.indexState.offset;
10634
+ }
10635
+ });
10636
+ }).next(() => offset);
10637
+ }
10581
10638
  }
10582
10639
  /**
10583
10640
  * Helper to get a typed SimpleDbStore for the collectionParents
@@ -12327,12 +12384,31 @@ function dbCollectionGroupKey(collectionGroup, offset) {
12327
12384
  }
12328
12385
  /**
12329
12386
  * Comparator that compares document keys according to the primary key sorting
12330
- * used by the `DbRemoteDocumentDocument` store (by collection path and then
12331
- * document ID).
12387
+ * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
12388
+ * and then document ID).
12389
+ *
12390
+ * Visible for testing.
12332
12391
  */
12333
12392
  function dbKeyComparator(l, r) {
12334
- const cmp = l.path.length - r.path.length;
12335
- return cmp !== 0 ? cmp : DocumentKey.comparator(l, r);
12393
+ const left = l.path.toArray();
12394
+ const right = r.path.toArray();
12395
+ // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
12396
+ let cmp = 0;
12397
+ for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {
12398
+ cmp = primitiveComparator(left[i], right[i]);
12399
+ if (cmp) {
12400
+ return cmp;
12401
+ }
12402
+ }
12403
+ cmp = primitiveComparator(left.length, right.length);
12404
+ if (cmp) {
12405
+ return cmp;
12406
+ }
12407
+ cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);
12408
+ if (cmp) {
12409
+ return cmp;
12410
+ }
12411
+ return primitiveComparator(left[left.length - 1], right[right.length - 1]);
12336
12412
  }
12337
12413
  /**
12338
12414
  * Schema Version for the Web client:
@@ -13729,7 +13805,7 @@ class LocalStoreImpl {
13729
13805
  this.mutationQueue = this.persistence.getMutationQueue(user, this.indexManager);
13730
13806
  this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.indexManager);
13731
13807
  this.remoteDocuments.setIndexManager(this.indexManager);
13732
- this.queryEngine.setLocalDocumentsView(this.localDocuments);
13808
+ this.queryEngine.initialize(this.localDocuments, this.indexManager);
13733
13809
  }
13734
13810
  collectGarbage(garbageCollector) {
13735
13811
  return this.persistence.runTransaction('Collect garbage', 'readwrite-primary', txn => garbageCollector.collect(txn, this.targetDataByTarget));
@@ -15471,10 +15547,30 @@ class MemoryEagerDelegate {
15471
15547
  * limitations under the License.
15472
15548
  */
15473
15549
  /**
15474
- * A query engine that takes advantage of the target document mapping in the
15475
- * QueryCache. Query execution is optimized by only reading the documents that
15476
- * previously matched a query plus any documents that were edited after the
15477
- * query was last listened to.
15550
+ * The Firestore query engine.
15551
+ *
15552
+ * Firestore queries can be executed in three modes. The Query Engine determines
15553
+ * what mode to use based on what data is persisted. The mode only determines
15554
+ * the runtime complexity of the query - the result set is equivalent across all
15555
+ * implementations.
15556
+ *
15557
+ * The Query engine will use indexed-based execution if a user has configured
15558
+ * any index that can be used to execute query (via `setIndexConfiguration()`).
15559
+ * Otherwise, the engine will try to optimize the query by re-using a previously
15560
+ * persisted query result. If that is not possible, the query will be executed
15561
+ * via a full collection scan.
15562
+ *
15563
+ * Index-based execution is the default when available. The query engine
15564
+ * supports partial indexed execution and merges the result from the index
15565
+ * lookup with documents that have not yet been indexed. The index evaluation
15566
+ * matches the backend's format and as such, the SDK can use indexing for all
15567
+ * queries that the backend supports.
15568
+ *
15569
+ * If no index exists, the query engine tries to take advantage of the target
15570
+ * document mapping in the TargetCache. These mappings exists for all queries
15571
+ * that have been synced with the backend at least once and allow the query
15572
+ * engine to only read documents that previously matched a query plus any
15573
+ * documents that were edited after the query was last listened to.
15478
15574
  *
15479
15575
  * There are some cases when this optimization is not guaranteed to produce
15480
15576
  * the same results as full collection scans. In these cases, query
@@ -15489,16 +15585,41 @@ class MemoryEagerDelegate {
15489
15585
  * - Queries that have never been CURRENT or free of limbo documents.
15490
15586
  */
15491
15587
  class QueryEngine {
15588
+ constructor() {
15589
+ this.initialized = false;
15590
+ }
15492
15591
  /** Sets the document view to query against. */
15493
- setLocalDocumentsView(localDocuments) {
15592
+ initialize(localDocuments, indexManager) {
15494
15593
  this.localDocumentsView = localDocuments;
15594
+ this.indexManager = indexManager;
15595
+ this.initialized = true;
15495
15596
  }
15496
15597
  /** Returns all local documents matching the specified query. */
15497
15598
  getDocumentsMatchingQuery(transaction, query, lastLimboFreeSnapshotVersion, remoteKeys) {
15498
- // Queries that match all documents don't benefit from using
15499
- // key-based lookups. It is more efficient to scan all documents in a
15500
- // collection, rather than to perform individual lookups.
15501
- if (matchesAllDocuments(query)) {
15599
+ return this.performQueryUsingIndex(transaction, query)
15600
+ .next(result => result
15601
+ ? result
15602
+ : this.performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion))
15603
+ .next(result => result ? result : this.executeFullCollectionScan(transaction, query));
15604
+ }
15605
+ /**
15606
+ * Performs an indexed query that evaluates the query based on a collection's
15607
+ * persisted index values. Returns `null` if an index is not available.
15608
+ */
15609
+ performQueryUsingIndex(transaction, query) {
15610
+ {
15611
+ return PersistencePromise.resolve(null);
15612
+ }
15613
+ }
15614
+ /**
15615
+ * Performs a query based on the target's persisted query mapping. Returns
15616
+ * `null` if the mapping is not available or cannot be used.
15617
+ */
15618
+ performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion) {
15619
+ if (queryMatchesAllDocuments(query)) {
15620
+ // Queries that match all documents don't benefit from using
15621
+ // key-based lookups. It is more efficient to scan all documents in a
15622
+ // collection, rather than to perform individual lookups.
15502
15623
  return this.executeFullCollectionScan(transaction, query);
15503
15624
  }
15504
15625
  // Queries that have never seen a snapshot without limbo free documents
@@ -15508,8 +15629,7 @@ class QueryEngine {
15508
15629
  }
15509
15630
  return this.localDocumentsView.getDocuments(transaction, remoteKeys).next(documents => {
15510
15631
  const previousResults = this.applyQuery(query, documents);
15511
- if ((hasLimitToFirst(query) || hasLimitToLast(query)) &&
15512
- this.needsRefill(query.limitType, previousResults, remoteKeys, lastLimboFreeSnapshotVersion)) {
15632
+ if (this.needsRefill(query, previousResults, remoteKeys, lastLimboFreeSnapshotVersion)) {
15513
15633
  return this.executeFullCollectionScan(transaction, query);
15514
15634
  }
15515
15635
  if (getLogLevel() <= logger.LogLevel.DEBUG) {
@@ -15517,15 +15637,7 @@ class QueryEngine {
15517
15637
  }
15518
15638
  // Retrieve all results for documents that were updated since the last
15519
15639
  // limbo-document free remote snapshot.
15520
- return this.localDocumentsView.getDocumentsMatchingQuery(transaction, query, newIndexOffsetSuccessorFromReadTime(lastLimboFreeSnapshotVersion, INITIAL_LARGEST_BATCH_ID)).next(updatedResults => {
15521
- // We merge `previousResults` into `updateResults`, since
15522
- // `updateResults` is already a DocumentMap. If a document is
15523
- // contained in both lists, then its contents are the same.
15524
- previousResults.forEach(doc => {
15525
- updatedResults = updatedResults.insert(doc.key, doc);
15526
- });
15527
- return updatedResults;
15528
- });
15640
+ return this.appendRemainingResults(transaction, previousResults, query, newIndexOffsetSuccessorFromReadTime(lastLimboFreeSnapshotVersion, INITIAL_LARGEST_BATCH_ID));
15529
15641
  });
15530
15642
  }
15531
15643
  /** Applies the query filter and sorting to the provided documents. */
@@ -15544,6 +15656,7 @@ class QueryEngine {
15544
15656
  * Determines if a limit query needs to be refilled from cache, making it
15545
15657
  * ineligible for index-free execution.
15546
15658
  *
15659
+ * @param query The query.
15547
15660
  * @param sortedPreviousResults - The documents that matched the query when it
15548
15661
  * was last synchronized, sorted by the query's comparator.
15549
15662
  * @param remoteKeys - The document keys that matched the query at the last
@@ -15551,10 +15664,14 @@ class QueryEngine {
15551
15664
  * @param limboFreeSnapshotVersion - The version of the snapshot when the
15552
15665
  * query was last synchronized.
15553
15666
  */
15554
- needsRefill(limitType, sortedPreviousResults, remoteKeys, limboFreeSnapshotVersion) {
15555
- // The query needs to be refilled if a previously matching document no
15556
- // longer matches.
15667
+ needsRefill(query, sortedPreviousResults, remoteKeys, limboFreeSnapshotVersion) {
15668
+ if (query.limit === null) {
15669
+ // Queries without limits do not need to be refilled.
15670
+ return false;
15671
+ }
15557
15672
  if (remoteKeys.size !== sortedPreviousResults.size) {
15673
+ // The query needs to be refilled if a previously matching document no
15674
+ // longer matches.
15558
15675
  return true;
15559
15676
  }
15560
15677
  // Limit queries are not eligible for index-free query execution if there is
@@ -15565,7 +15682,7 @@ class QueryEngine {
15565
15682
  // the boundary of the limit itself did not change and documents from cache
15566
15683
  // will continue to be "rejected" by this boundary. Therefore, we can ignore
15567
15684
  // any modifications that don't affect the last document.
15568
- const docAtLimitEdge = limitType === "F" /* First */
15685
+ const docAtLimitEdge = query.limitType === "F" /* First */
15569
15686
  ? sortedPreviousResults.last()
15570
15687
  : sortedPreviousResults.first();
15571
15688
  if (!docAtLimitEdge) {
@@ -15581,6 +15698,22 @@ class QueryEngine {
15581
15698
  }
15582
15699
  return this.localDocumentsView.getDocumentsMatchingQuery(transaction, query, IndexOffset.min());
15583
15700
  }
15701
+ /**
15702
+ * Combines the results from an indexed execution with the remaining documents
15703
+ * that have not yet been indexed.
15704
+ */
15705
+ appendRemainingResults(transaction, indexedResults, query, offset) {
15706
+ // Retrieve all results for documents that were updated since the offset.
15707
+ return this.localDocumentsView
15708
+ .getDocumentsMatchingQuery(transaction, query, offset)
15709
+ .next(remainingResults => {
15710
+ // Merge with existing results
15711
+ indexedResults.forEach(d => {
15712
+ remainingResults = remainingResults.insert(d.key, d);
15713
+ });
15714
+ return remainingResults;
15715
+ });
15716
+ }
15584
15717
  }
15585
15718
 
15586
15719
  /**
@@ -21840,10 +21973,12 @@ class View {
21840
21973
  //
21841
21974
  // Note that this should never get used in a refill (when previousChanges is
21842
21975
  // set), because there will only be adds -- no deletes or updates.
21843
- const lastDocInLimit = hasLimitToFirst(this.query) && oldDocumentSet.size === this.query.limit
21976
+ const lastDocInLimit = this.query.limitType === "F" /* First */ &&
21977
+ oldDocumentSet.size === this.query.limit
21844
21978
  ? oldDocumentSet.last()
21845
21979
  : null;
21846
- const firstDocInLimit = hasLimitToLast(this.query) && oldDocumentSet.size === this.query.limit
21980
+ const firstDocInLimit = this.query.limitType === "L" /* Last */ &&
21981
+ oldDocumentSet.size === this.query.limit
21847
21982
  ? oldDocumentSet.first()
21848
21983
  : null;
21849
21984
  docChanges.inorderTraversal((key, entry) => {
@@ -21916,9 +22051,9 @@ class View {
21916
22051
  }
21917
22052
  });
21918
22053
  // Drop documents out to meet limit/limitToLast requirement.
21919
- if (hasLimitToFirst(this.query) || hasLimitToLast(this.query)) {
22054
+ if (this.query.limit !== null) {
21920
22055
  while (newDocumentSet.size > this.query.limit) {
21921
- const oldDoc = hasLimitToFirst(this.query)
22056
+ const oldDoc = this.query.limitType === "F" /* First */
21922
22057
  ? newDocumentSet.last()
21923
22058
  : newDocumentSet.first();
21924
22059
  newDocumentSet = newDocumentSet.delete(oldDoc.key);
@@ -27049,7 +27184,8 @@ function snapshotEqual(left, right) {
27049
27184
  * limitations under the License.
27050
27185
  */
27051
27186
  function validateHasExplicitOrderByForLimitToLast(query) {
27052
- if (hasLimitToLast(query) && query.explicitOrderBy.length === 0) {
27187
+ if (query.limitType === "L" /* Last */ &&
27188
+ query.explicitOrderBy.length === 0) {
27053
27189
  throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
27054
27190
  }
27055
27191
  }