@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
@@ -8,7 +8,7 @@ import * as grpc from '@grpc/grpc-js';
8
8
  import * as protoLoader from '@grpc/proto-loader';
9
9
 
10
10
  const name = "@firebase/firestore";
11
- const version$1 = "3.4.7-canary.e9e5f6b3c";
11
+ const version$1 = "3.4.8-canary.215e657ea";
12
12
 
13
13
  /**
14
14
  * @license
@@ -61,7 +61,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
61
61
  User.FIRST_PARTY = new User('first-party-uid');
62
62
  User.MOCK_USER = new User('mock-user');
63
63
 
64
- const version = "9.6.10-canary.e9e5f6b3c";
64
+ const version = "9.6.11-canary.215e657ea";
65
65
 
66
66
  /**
67
67
  * @license
@@ -2286,9 +2286,7 @@ class SimpleDbStore {
2286
2286
  cursor.continue(controller.skipToKey);
2287
2287
  }
2288
2288
  };
2289
- }).next(() => {
2290
- return PersistencePromise.waitFor(results);
2291
- });
2289
+ }).next(() => PersistencePromise.waitFor(results));
2292
2290
  }
2293
2291
  options(indexOrRange, range) {
2294
2292
  let indexName = undefined;
@@ -3323,7 +3321,7 @@ function typeOrder(value) {
3323
3321
  return 4 /* ServerTimestampValue */;
3324
3322
  }
3325
3323
  else if (isMaxValue(value)) {
3326
- return 9 /* ArrayValue */;
3324
+ return 9007199254740991 /* MaxValue */;
3327
3325
  }
3328
3326
  return 10 /* ObjectValue */;
3329
3327
  }
@@ -3535,6 +3533,15 @@ function compareArrays(left, right) {
3535
3533
  return primitiveComparator(leftArray.length, rightArray.length);
3536
3534
  }
3537
3535
  function compareMaps(left, right) {
3536
+ if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {
3537
+ return 0;
3538
+ }
3539
+ else if (left === MAX_VALUE.mapValue) {
3540
+ return 1;
3541
+ }
3542
+ else if (right === MAX_VALUE.mapValue) {
3543
+ return -1;
3544
+ }
3538
3545
  const leftMap = left.fields || {};
3539
3546
  const leftKeys = Object.keys(leftMap);
3540
3547
  const rightMap = right.fields || {};
@@ -3782,27 +3789,31 @@ function valuesGetUpperBound(value) {
3782
3789
  return fail();
3783
3790
  }
3784
3791
  }
3785
- function valuesMax(left, right) {
3786
- if (left === undefined) {
3787
- return right;
3792
+ function lowerBoundCompare(left, right) {
3793
+ const cmp = valueCompare(left.value, right.value);
3794
+ if (cmp !== 0) {
3795
+ return cmp;
3788
3796
  }
3789
- else if (right === undefined) {
3790
- return left;
3797
+ if (left.inclusive && !right.inclusive) {
3798
+ return -1;
3791
3799
  }
3792
- else {
3793
- return valueCompare(left, right) > 0 ? left : right;
3800
+ else if (!left.inclusive && right.inclusive) {
3801
+ return 1;
3794
3802
  }
3803
+ return 0;
3795
3804
  }
3796
- function valuesMin(left, right) {
3797
- if (left === undefined) {
3798
- return right;
3805
+ function upperBoundCompare(left, right) {
3806
+ const cmp = valueCompare(left.value, right.value);
3807
+ if (cmp !== 0) {
3808
+ return cmp;
3799
3809
  }
3800
- else if (right === undefined) {
3801
- return left;
3810
+ if (left.inclusive && !right.inclusive) {
3811
+ return 1;
3802
3812
  }
3803
- else {
3804
- return valueCompare(left, right) < 0 ? left : right;
3813
+ else if (!left.inclusive && right.inclusive) {
3814
+ return -1;
3805
3815
  }
3816
+ return 0;
3806
3817
  }
3807
3818
 
3808
3819
  /**
@@ -4312,7 +4323,7 @@ function indexOffsetComparator(left, right) {
4312
4323
 
4313
4324
  /**
4314
4325
  * @license
4315
- * Copyright 2019 Google LLC
4326
+ * Copyright 2017 Google LLC
4316
4327
  *
4317
4328
  * Licensed under the Apache License, Version 2.0 (the "License");
4318
4329
  * you may not use this file except in compliance with the License.
@@ -4326,609 +4337,445 @@ function indexOffsetComparator(left, right) {
4326
4337
  * See the License for the specific language governing permissions and
4327
4338
  * limitations under the License.
4328
4339
  */
4329
- // Visible for testing
4330
- class TargetImpl {
4331
- constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4332
- this.path = path;
4333
- this.collectionGroup = collectionGroup;
4334
- this.orderBy = orderBy;
4335
- this.filters = filters;
4336
- this.limit = limit;
4337
- this.startAt = startAt;
4338
- this.endAt = endAt;
4339
- this.memoizedCanonicalId = null;
4340
+ // An immutable sorted map implementation, based on a Left-leaning Red-Black
4341
+ // tree.
4342
+ class SortedMap {
4343
+ constructor(comparator, root) {
4344
+ this.comparator = comparator;
4345
+ this.root = root ? root : LLRBNode.EMPTY;
4340
4346
  }
4341
- }
4342
- /**
4343
- * Initializes a Target with a path and optional additional query constraints.
4344
- * Path must currently be empty if this is a collection group query.
4345
- *
4346
- * NOTE: you should always construct `Target` from `Query.toTarget` instead of
4347
- * using this factory method, because `Query` provides an implicit `orderBy`
4348
- * property.
4349
- */
4350
- function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4351
- return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
4352
- }
4353
- function canonifyTarget(target) {
4354
- const targetImpl = debugCast(target);
4355
- if (targetImpl.memoizedCanonicalId === null) {
4356
- let str = targetImpl.path.canonicalString();
4357
- if (targetImpl.collectionGroup !== null) {
4358
- str += '|cg:' + targetImpl.collectionGroup;
4359
- }
4360
- str += '|f:';
4361
- str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
4362
- str += '|ob:';
4363
- str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
4364
- if (!isNullOrUndefined(targetImpl.limit)) {
4365
- str += '|l:';
4366
- str += targetImpl.limit;
4367
- }
4368
- if (targetImpl.startAt) {
4369
- str += '|lb:';
4370
- str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
4371
- str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
4372
- }
4373
- if (targetImpl.endAt) {
4374
- str += '|ub:';
4375
- str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
4376
- str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
4377
- }
4378
- targetImpl.memoizedCanonicalId = str;
4347
+ // Returns a copy of the map, with the specified key/value added or replaced.
4348
+ insert(key, value) {
4349
+ return new SortedMap(this.comparator, this.root
4350
+ .insert(key, value, this.comparator)
4351
+ .copy(null, null, LLRBNode.BLACK, null, null));
4379
4352
  }
4380
- return targetImpl.memoizedCanonicalId;
4381
- }
4382
- function stringifyTarget(target) {
4383
- let str = target.path.canonicalString();
4384
- if (target.collectionGroup !== null) {
4385
- str += ' collectionGroup=' + target.collectionGroup;
4353
+ // Returns a copy of the map, with the specified key removed.
4354
+ remove(key) {
4355
+ return new SortedMap(this.comparator, this.root
4356
+ .remove(key, this.comparator)
4357
+ .copy(null, null, LLRBNode.BLACK, null, null));
4386
4358
  }
4387
- if (target.filters.length > 0) {
4388
- str += `, filters: [${target.filters
4389
- .map(f => stringifyFilter(f))
4390
- .join(', ')}]`;
4359
+ // Returns the value of the node with the given key, or null.
4360
+ get(key) {
4361
+ let node = this.root;
4362
+ while (!node.isEmpty()) {
4363
+ const cmp = this.comparator(key, node.key);
4364
+ if (cmp === 0) {
4365
+ return node.value;
4366
+ }
4367
+ else if (cmp < 0) {
4368
+ node = node.left;
4369
+ }
4370
+ else if (cmp > 0) {
4371
+ node = node.right;
4372
+ }
4373
+ }
4374
+ return null;
4391
4375
  }
4392
- if (!isNullOrUndefined(target.limit)) {
4393
- str += ', limit: ' + target.limit;
4376
+ // Returns the index of the element in this sorted map, or -1 if it doesn't
4377
+ // exist.
4378
+ indexOf(key) {
4379
+ // Number of nodes that were pruned when descending right
4380
+ let prunedNodes = 0;
4381
+ let node = this.root;
4382
+ while (!node.isEmpty()) {
4383
+ const cmp = this.comparator(key, node.key);
4384
+ if (cmp === 0) {
4385
+ return prunedNodes + node.left.size;
4386
+ }
4387
+ else if (cmp < 0) {
4388
+ node = node.left;
4389
+ }
4390
+ else {
4391
+ // Count all nodes left of the node plus the node itself
4392
+ prunedNodes += node.left.size + 1;
4393
+ node = node.right;
4394
+ }
4395
+ }
4396
+ // Node not found
4397
+ return -1;
4394
4398
  }
4395
- if (target.orderBy.length > 0) {
4396
- str += `, orderBy: [${target.orderBy
4397
- .map(o => stringifyOrderBy(o))
4398
- .join(', ')}]`;
4399
+ isEmpty() {
4400
+ return this.root.isEmpty();
4399
4401
  }
4400
- if (target.startAt) {
4401
- str += ', startAt: ';
4402
- str += target.startAt.inclusive ? 'b:' : 'a:';
4403
- str += target.startAt.position.map(p => canonicalId(p)).join(',');
4402
+ // Returns the total number of nodes in the map.
4403
+ get size() {
4404
+ return this.root.size;
4404
4405
  }
4405
- if (target.endAt) {
4406
- str += ', endAt: ';
4407
- str += target.endAt.inclusive ? 'a:' : 'b:';
4408
- str += target.endAt.position.map(p => canonicalId(p)).join(',');
4406
+ // Returns the minimum key in the map.
4407
+ minKey() {
4408
+ return this.root.minKey();
4409
4409
  }
4410
- return `Target(${str})`;
4411
- }
4412
- function targetEquals(left, right) {
4413
- if (left.limit !== right.limit) {
4414
- return false;
4410
+ // Returns the maximum key in the map.
4411
+ maxKey() {
4412
+ return this.root.maxKey();
4415
4413
  }
4416
- if (left.orderBy.length !== right.orderBy.length) {
4417
- return false;
4414
+ // Traverses the map in key order and calls the specified action function
4415
+ // for each key/value pair. If action returns true, traversal is aborted.
4416
+ // Returns the first truthy value returned by action, or the last falsey
4417
+ // value returned by action.
4418
+ inorderTraversal(action) {
4419
+ return this.root.inorderTraversal(action);
4418
4420
  }
4419
- for (let i = 0; i < left.orderBy.length; i++) {
4420
- if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
4421
+ forEach(fn) {
4422
+ this.inorderTraversal((k, v) => {
4423
+ fn(k, v);
4421
4424
  return false;
4422
- }
4423
- }
4424
- if (left.filters.length !== right.filters.length) {
4425
- return false;
4425
+ });
4426
4426
  }
4427
- for (let i = 0; i < left.filters.length; i++) {
4428
- if (!filterEquals(left.filters[i], right.filters[i])) {
4427
+ toString() {
4428
+ const descriptions = [];
4429
+ this.inorderTraversal((k, v) => {
4430
+ descriptions.push(`${k}:${v}`);
4429
4431
  return false;
4430
- }
4432
+ });
4433
+ return `{${descriptions.join(', ')}}`;
4431
4434
  }
4432
- if (left.collectionGroup !== right.collectionGroup) {
4433
- return false;
4435
+ // Traverses the map in reverse key order and calls the specified action
4436
+ // function for each key/value pair. If action returns true, traversal is
4437
+ // aborted.
4438
+ // Returns the first truthy value returned by action, or the last falsey
4439
+ // value returned by action.
4440
+ reverseTraversal(action) {
4441
+ return this.root.reverseTraversal(action);
4434
4442
  }
4435
- if (!left.path.isEqual(right.path)) {
4436
- return false;
4443
+ // Returns an iterator over the SortedMap.
4444
+ getIterator() {
4445
+ return new SortedMapIterator(this.root, null, this.comparator, false);
4437
4446
  }
4438
- if (!boundEquals(left.startAt, right.startAt)) {
4439
- return false;
4447
+ getIteratorFrom(key) {
4448
+ return new SortedMapIterator(this.root, key, this.comparator, false);
4440
4449
  }
4441
- return boundEquals(left.endAt, right.endAt);
4442
- }
4443
- function targetIsDocumentTarget(target) {
4444
- return (DocumentKey.isDocumentKey(target.path) &&
4445
- target.collectionGroup === null &&
4446
- target.filters.length === 0);
4447
- }
4448
- /** Returns the field filters that target the given field path. */
4449
- function targetGetFieldFiltersForPath(target, path) {
4450
- return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
4451
- }
4452
- /**
4453
- * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
4454
- * filters. Returns `null` if there are no such filters.
4455
- */
4456
- function targetGetArrayValues(target, fieldIndex) {
4457
- const segment = fieldIndexGetArraySegment(fieldIndex);
4458
- if (segment === undefined) {
4459
- return null;
4450
+ getReverseIterator() {
4451
+ return new SortedMapIterator(this.root, null, this.comparator, true);
4460
4452
  }
4461
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4462
- switch (fieldFilter.op) {
4463
- case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
4464
- return fieldFilter.value.arrayValue.values || [];
4465
- case "array-contains" /* ARRAY_CONTAINS */:
4466
- return [fieldFilter.value];
4467
- // Remaining filters are not array filters.
4468
- }
4453
+ getReverseIteratorFrom(key) {
4454
+ return new SortedMapIterator(this.root, key, this.comparator, true);
4469
4455
  }
4470
- return null;
4471
- }
4472
- /**
4473
- * Returns the list of values that are used in != or NOT_IN filters. Returns
4474
- * `null` if there are no such filters.
4475
- */
4476
- function targetGetNotInValues(target, fieldIndex) {
4477
- const values = new Map();
4478
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4479
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4480
- switch (fieldFilter.op) {
4481
- case "==" /* EQUAL */:
4482
- case "in" /* IN */:
4483
- // Encode equality prefix, which is encoded in the index value before
4484
- // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
4485
- // `value != 'ab'`).
4486
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4487
- break;
4488
- case "not-in" /* NOT_IN */:
4489
- case "!=" /* NOT_EQUAL */:
4490
- // NotIn/NotEqual is always a suffix. There cannot be any remaining
4491
- // segments and hence we can return early here.
4492
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4493
- return Array.from(values.values());
4494
- // Remaining filters cannot be used as notIn bounds.
4456
+ } // end SortedMap
4457
+ // An iterator over an LLRBNode.
4458
+ class SortedMapIterator {
4459
+ constructor(node, startKey, comparator, isReverse) {
4460
+ this.isReverse = isReverse;
4461
+ this.nodeStack = [];
4462
+ let cmp = 1;
4463
+ while (!node.isEmpty()) {
4464
+ cmp = startKey ? comparator(node.key, startKey) : 1;
4465
+ // flip the comparison if we're going in reverse
4466
+ if (startKey && isReverse) {
4467
+ cmp *= -1;
4468
+ }
4469
+ if (cmp < 0) {
4470
+ // This node is less than our start key. ignore it
4471
+ if (this.isReverse) {
4472
+ node = node.left;
4473
+ }
4474
+ else {
4475
+ node = node.right;
4476
+ }
4477
+ }
4478
+ else if (cmp === 0) {
4479
+ // This node is exactly equal to our start key. Push it on the stack,
4480
+ // but stop iterating;
4481
+ this.nodeStack.push(node);
4482
+ break;
4483
+ }
4484
+ else {
4485
+ // This node is greater than our start key, add it to the stack and move
4486
+ // to the next one
4487
+ this.nodeStack.push(node);
4488
+ if (this.isReverse) {
4489
+ node = node.right;
4490
+ }
4491
+ else {
4492
+ node = node.left;
4493
+ }
4495
4494
  }
4496
4495
  }
4497
4496
  }
4498
- return null;
4499
- }
4500
- /**
4501
- * Returns a lower bound of field values that can be used as a starting point to
4502
- * scan the index defined by `fieldIndex`. Returns `null` if no lower bound
4503
- * exists.
4504
- */
4505
- function targetGetLowerBound(target, fieldIndex) {
4506
- const values = [];
4507
- let inclusive = true;
4508
- // For each segment, retrieve a lower bound if there is a suitable filter or
4509
- // startAt.
4510
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4511
- const segmentBound = segment.kind === 0 /* ASCENDING */
4512
- ? targetGetLowerBoundForField(target, segment.fieldPath, target.startAt)
4513
- : targetGetUpperBoundForField(target, segment.fieldPath, target.startAt);
4514
- if (!segmentBound.value) {
4515
- // No lower bound exists
4516
- return null;
4497
+ getNext() {
4498
+ let node = this.nodeStack.pop();
4499
+ const result = { key: node.key, value: node.value };
4500
+ if (this.isReverse) {
4501
+ node = node.left;
4502
+ while (!node.isEmpty()) {
4503
+ this.nodeStack.push(node);
4504
+ node = node.right;
4505
+ }
4517
4506
  }
4518
- values.push(segmentBound.value);
4519
- inclusive && (inclusive = segmentBound.inclusive);
4507
+ else {
4508
+ node = node.right;
4509
+ while (!node.isEmpty()) {
4510
+ this.nodeStack.push(node);
4511
+ node = node.left;
4512
+ }
4513
+ }
4514
+ return result;
4520
4515
  }
4521
- return new Bound(values, inclusive);
4522
- }
4523
- /**
4524
- * Returns an upper bound of field values that can be used as an ending point
4525
- * when scanning the index defined by `fieldIndex`. Returns `null` if no
4526
- * upper bound exists.
4527
- */
4528
- function targetGetUpperBound(target, fieldIndex) {
4529
- const values = [];
4530
- let inclusive = true;
4531
- // For each segment, retrieve an upper bound if there is a suitable filter or
4532
- // endAt.
4533
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4534
- const segmentBound = segment.kind === 0 /* ASCENDING */
4535
- ? targetGetUpperBoundForField(target, segment.fieldPath, target.endAt)
4536
- : targetGetLowerBoundForField(target, segment.fieldPath, target.endAt);
4537
- if (!segmentBound.value) {
4538
- // No upper bound exists
4516
+ hasNext() {
4517
+ return this.nodeStack.length > 0;
4518
+ }
4519
+ peek() {
4520
+ if (this.nodeStack.length === 0) {
4539
4521
  return null;
4540
4522
  }
4541
- values.push(segmentBound.value);
4542
- inclusive && (inclusive = segmentBound.inclusive);
4523
+ const node = this.nodeStack[this.nodeStack.length - 1];
4524
+ return { key: node.key, value: node.value };
4543
4525
  }
4544
- return new Bound(values, inclusive);
4545
- }
4546
- /**
4547
- * Returns the value to use as the lower bound for ascending index segment at
4548
- * the provided `fieldPath` (or the upper bound for an descending segment).
4549
- */
4550
- function targetGetLowerBoundForField(target, fieldPath, bound) {
4551
- let value = undefined;
4552
- let inclusive = true;
4553
- // Process all filters to find a value for the current field segment
4554
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4555
- let filterValue = undefined;
4556
- let filterInclusive = true;
4557
- switch (fieldFilter.op) {
4558
- case "<" /* LESS_THAN */:
4559
- case "<=" /* LESS_THAN_OR_EQUAL */:
4560
- filterValue = valuesGetLowerBound(fieldFilter.value);
4561
- break;
4562
- case "==" /* EQUAL */:
4563
- case "in" /* IN */:
4564
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4565
- filterValue = fieldFilter.value;
4566
- break;
4567
- case ">" /* GREATER_THAN */:
4568
- filterValue = fieldFilter.value;
4569
- filterInclusive = false;
4570
- break;
4571
- case "!=" /* NOT_EQUAL */:
4572
- case "not-in" /* NOT_IN */:
4573
- filterValue = MIN_VALUE;
4574
- break;
4575
- // Remaining filters cannot be used as lower bounds.
4526
+ } // end SortedMapIterator
4527
+ // Represents a node in a Left-leaning Red-Black tree.
4528
+ class LLRBNode {
4529
+ constructor(key, value, color, left, right) {
4530
+ this.key = key;
4531
+ this.value = value;
4532
+ this.color = color != null ? color : LLRBNode.RED;
4533
+ this.left = left != null ? left : LLRBNode.EMPTY;
4534
+ this.right = right != null ? right : LLRBNode.EMPTY;
4535
+ this.size = this.left.size + 1 + this.right.size;
4536
+ }
4537
+ // Returns a copy of the current node, optionally replacing pieces of it.
4538
+ copy(key, value, color, left, right) {
4539
+ 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);
4540
+ }
4541
+ isEmpty() {
4542
+ return false;
4543
+ }
4544
+ // Traverses the tree in key order and calls the specified action function
4545
+ // for each node. If action returns true, traversal is aborted.
4546
+ // Returns the first truthy value returned by action, or the last falsey
4547
+ // value returned by action.
4548
+ inorderTraversal(action) {
4549
+ return (this.left.inorderTraversal(action) ||
4550
+ action(this.key, this.value) ||
4551
+ this.right.inorderTraversal(action));
4552
+ }
4553
+ // Traverses the tree in reverse key order and calls the specified action
4554
+ // function for each node. If action returns true, traversal is aborted.
4555
+ // Returns the first truthy value returned by action, or the last falsey
4556
+ // value returned by action.
4557
+ reverseTraversal(action) {
4558
+ return (this.right.reverseTraversal(action) ||
4559
+ action(this.key, this.value) ||
4560
+ this.left.reverseTraversal(action));
4561
+ }
4562
+ // Returns the minimum node in the tree.
4563
+ min() {
4564
+ if (this.left.isEmpty()) {
4565
+ return this;
4576
4566
  }
4577
- if (valuesMax(value, filterValue) === filterValue) {
4578
- value = filterValue;
4579
- inclusive = filterInclusive;
4567
+ else {
4568
+ return this.left.min();
4580
4569
  }
4581
4570
  }
4582
- // If there is an additional bound, compare the values against the existing
4583
- // range to see if we can narrow the scope.
4584
- if (bound !== null) {
4585
- for (let i = 0; i < target.orderBy.length; ++i) {
4586
- const orderBy = target.orderBy[i];
4587
- if (orderBy.field.isEqual(fieldPath)) {
4588
- const cursorValue = bound.position[i];
4589
- if (valuesMax(value, cursorValue) === cursorValue) {
4590
- value = cursorValue;
4591
- inclusive = bound.inclusive;
4592
- }
4593
- break;
4594
- }
4595
- }
4571
+ // Returns the maximum key in the tree.
4572
+ minKey() {
4573
+ return this.min().key;
4596
4574
  }
4597
- return { value, inclusive };
4598
- }
4599
- /**
4600
- * Returns the value to use as the upper bound for ascending index segment at
4601
- * the provided `fieldPath` (or the lower bound for an descending segment).
4602
- */
4603
- function targetGetUpperBoundForField(target, fieldPath, bound) {
4604
- let value = undefined;
4605
- let inclusive = true;
4606
- // Process all filters to find a value for the current field segment
4607
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4608
- let filterValue = undefined;
4609
- let filterInclusive = true;
4610
- switch (fieldFilter.op) {
4611
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4612
- case ">" /* GREATER_THAN */:
4613
- filterValue = valuesGetUpperBound(fieldFilter.value);
4614
- filterInclusive = false;
4615
- break;
4616
- case "==" /* EQUAL */:
4617
- case "in" /* IN */:
4618
- case "<=" /* LESS_THAN_OR_EQUAL */:
4619
- filterValue = fieldFilter.value;
4620
- break;
4621
- case "<" /* LESS_THAN */:
4622
- filterValue = fieldFilter.value;
4623
- filterInclusive = false;
4624
- break;
4625
- case "!=" /* NOT_EQUAL */:
4626
- case "not-in" /* NOT_IN */:
4627
- filterValue = MAX_VALUE;
4628
- break;
4629
- // Remaining filters cannot be used as upper bounds.
4575
+ // Returns the maximum key in the tree.
4576
+ maxKey() {
4577
+ if (this.right.isEmpty()) {
4578
+ return this.key;
4630
4579
  }
4631
- if (valuesMin(value, filterValue) === filterValue) {
4632
- value = filterValue;
4633
- inclusive = filterInclusive;
4580
+ else {
4581
+ return this.right.maxKey();
4634
4582
  }
4635
4583
  }
4636
- // If there is an additional bound, compare the values against the existing
4637
- // range to see if we can narrow the scope.
4638
- if (bound !== null) {
4639
- for (let i = 0; i < target.orderBy.length; ++i) {
4640
- const orderBy = target.orderBy[i];
4641
- if (orderBy.field.isEqual(fieldPath)) {
4642
- const cursorValue = bound.position[i];
4643
- if (valuesMin(value, cursorValue) === cursorValue) {
4644
- value = cursorValue;
4645
- inclusive = bound.inclusive;
4646
- }
4647
- break;
4648
- }
4584
+ // Returns new tree, with the key/value added.
4585
+ insert(key, value, comparator) {
4586
+ let n = this;
4587
+ const cmp = comparator(key, n.key);
4588
+ if (cmp < 0) {
4589
+ n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
4590
+ }
4591
+ else if (cmp === 0) {
4592
+ n = n.copy(null, value, null, null, null);
4593
+ }
4594
+ else {
4595
+ n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
4649
4596
  }
4597
+ return n.fixUp();
4650
4598
  }
4651
- return { value, inclusive };
4652
- }
4653
- class Filter {
4654
- }
4655
- class FieldFilter extends Filter {
4656
- constructor(field, op, value) {
4657
- super();
4658
- this.field = field;
4659
- this.op = op;
4660
- this.value = value;
4599
+ removeMin() {
4600
+ if (this.left.isEmpty()) {
4601
+ return LLRBNode.EMPTY;
4602
+ }
4603
+ let n = this;
4604
+ if (!n.left.isRed() && !n.left.left.isRed()) {
4605
+ n = n.moveRedLeft();
4606
+ }
4607
+ n = n.copy(null, null, null, n.left.removeMin(), null);
4608
+ return n.fixUp();
4661
4609
  }
4662
- /**
4663
- * Creates a filter based on the provided arguments.
4664
- */
4665
- static create(field, op, value) {
4666
- if (field.isKeyField()) {
4667
- if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
4668
- return this.createKeyFieldInFilter(field, op, value);
4610
+ // Returns new tree, with the specified item removed.
4611
+ remove(key, comparator) {
4612
+ let smallest;
4613
+ let n = this;
4614
+ if (comparator(key, n.key) < 0) {
4615
+ if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
4616
+ n = n.moveRedLeft();
4669
4617
  }
4670
- else {
4671
- return new KeyFieldFilter(field, op, value);
4618
+ n = n.copy(null, null, null, n.left.remove(key, comparator), null);
4619
+ }
4620
+ else {
4621
+ if (n.left.isRed()) {
4622
+ n = n.rotateRight();
4623
+ }
4624
+ if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
4625
+ n = n.moveRedRight();
4626
+ }
4627
+ if (comparator(key, n.key) === 0) {
4628
+ if (n.right.isEmpty()) {
4629
+ return LLRBNode.EMPTY;
4630
+ }
4631
+ else {
4632
+ smallest = n.right.min();
4633
+ n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
4634
+ }
4672
4635
  }
4636
+ n = n.copy(null, null, null, null, n.right.remove(key, comparator));
4673
4637
  }
4674
- else if (op === "array-contains" /* ARRAY_CONTAINS */) {
4675
- return new ArrayContainsFilter(field, value);
4638
+ return n.fixUp();
4639
+ }
4640
+ isRed() {
4641
+ return this.color;
4642
+ }
4643
+ // Returns new tree after performing any needed rotations.
4644
+ fixUp() {
4645
+ let n = this;
4646
+ if (n.right.isRed() && !n.left.isRed()) {
4647
+ n = n.rotateLeft();
4676
4648
  }
4677
- else if (op === "in" /* IN */) {
4678
- return new InFilter(field, value);
4649
+ if (n.left.isRed() && n.left.left.isRed()) {
4650
+ n = n.rotateRight();
4679
4651
  }
4680
- else if (op === "not-in" /* NOT_IN */) {
4681
- return new NotInFilter(field, value);
4652
+ if (n.left.isRed() && n.right.isRed()) {
4653
+ n = n.colorFlip();
4682
4654
  }
4683
- else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
4684
- return new ArrayContainsAnyFilter(field, value);
4655
+ return n;
4656
+ }
4657
+ moveRedLeft() {
4658
+ let n = this.colorFlip();
4659
+ if (n.right.left.isRed()) {
4660
+ n = n.copy(null, null, null, null, n.right.rotateRight());
4661
+ n = n.rotateLeft();
4662
+ n = n.colorFlip();
4685
4663
  }
4686
- else {
4687
- return new FieldFilter(field, op, value);
4664
+ return n;
4665
+ }
4666
+ moveRedRight() {
4667
+ let n = this.colorFlip();
4668
+ if (n.left.left.isRed()) {
4669
+ n = n.rotateRight();
4670
+ n = n.colorFlip();
4688
4671
  }
4672
+ return n;
4689
4673
  }
4690
- static createKeyFieldInFilter(field, op, value) {
4691
- return op === "in" /* IN */
4692
- ? new KeyFieldInFilter(field, value)
4693
- : new KeyFieldNotInFilter(field, value);
4674
+ rotateLeft() {
4675
+ const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
4676
+ return this.right.copy(null, null, this.color, nl, null);
4694
4677
  }
4695
- matches(doc) {
4696
- const other = doc.data.field(this.field);
4697
- // Types do not have to match in NOT_EQUAL filters.
4698
- if (this.op === "!=" /* NOT_EQUAL */) {
4699
- return (other !== null &&
4700
- this.matchesComparison(valueCompare(other, this.value)));
4678
+ rotateRight() {
4679
+ const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
4680
+ return this.left.copy(null, null, this.color, null, nr);
4681
+ }
4682
+ colorFlip() {
4683
+ const left = this.left.copy(null, null, !this.left.color, null, null);
4684
+ const right = this.right.copy(null, null, !this.right.color, null, null);
4685
+ return this.copy(null, null, !this.color, left, right);
4686
+ }
4687
+ // For testing.
4688
+ checkMaxDepth() {
4689
+ const blackDepth = this.check();
4690
+ if (Math.pow(2.0, blackDepth) <= this.size + 1) {
4691
+ return true;
4692
+ }
4693
+ else {
4694
+ return false;
4701
4695
  }
4702
- // Only compare types with matching backend order (such as double and int).
4703
- return (other !== null &&
4704
- typeOrder(this.value) === typeOrder(other) &&
4705
- this.matchesComparison(valueCompare(other, this.value)));
4706
4696
  }
4707
- matchesComparison(comparison) {
4708
- switch (this.op) {
4709
- case "<" /* LESS_THAN */:
4710
- return comparison < 0;
4711
- case "<=" /* LESS_THAN_OR_EQUAL */:
4712
- return comparison <= 0;
4713
- case "==" /* EQUAL */:
4714
- return comparison === 0;
4715
- case "!=" /* NOT_EQUAL */:
4716
- return comparison !== 0;
4717
- case ">" /* GREATER_THAN */:
4718
- return comparison > 0;
4719
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4720
- return comparison >= 0;
4721
- default:
4722
- return fail();
4697
+ // In a balanced RB tree, the black-depth (number of black nodes) from root to
4698
+ // leaves is equal on both sides. This function verifies that or asserts.
4699
+ check() {
4700
+ if (this.isRed() && this.left.isRed()) {
4701
+ throw fail();
4702
+ }
4703
+ if (this.right.isRed()) {
4704
+ throw fail();
4705
+ }
4706
+ const blackDepth = this.left.check();
4707
+ if (blackDepth !== this.right.check()) {
4708
+ throw fail();
4709
+ }
4710
+ else {
4711
+ return blackDepth + (this.isRed() ? 0 : 1);
4723
4712
  }
4724
4713
  }
4725
- isInequality() {
4726
- return ([
4727
- "<" /* LESS_THAN */,
4728
- "<=" /* LESS_THAN_OR_EQUAL */,
4729
- ">" /* GREATER_THAN */,
4730
- ">=" /* GREATER_THAN_OR_EQUAL */,
4731
- "!=" /* NOT_EQUAL */,
4732
- "not-in" /* NOT_IN */
4733
- ].indexOf(this.op) >= 0);
4714
+ } // end LLRBNode
4715
+ // Empty node is shared between all LLRB trees.
4716
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4717
+ LLRBNode.EMPTY = null;
4718
+ LLRBNode.RED = true;
4719
+ LLRBNode.BLACK = false;
4720
+ // Represents an empty node (a leaf node in the Red-Black Tree).
4721
+ class LLRBEmptyNode {
4722
+ constructor() {
4723
+ this.size = 0;
4734
4724
  }
4735
- }
4736
- function canonifyFilter(filter) {
4737
- // TODO(b/29183165): Technically, this won't be unique if two values have
4738
- // the same description, such as the int 3 and the string "3". So we should
4739
- // add the types in here somehow, too.
4740
- return (filter.field.canonicalString() +
4741
- filter.op.toString() +
4742
- canonicalId(filter.value));
4743
- }
4744
- function filterEquals(f1, f2) {
4745
- return (f1.op === f2.op &&
4746
- f1.field.isEqual(f2.field) &&
4747
- valueEquals(f1.value, f2.value));
4748
- }
4749
- /** Returns a debug description for `filter`. */
4750
- function stringifyFilter(filter) {
4751
- return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
4752
- }
4753
- /** Filter that matches on key fields (i.e. '__name__'). */
4754
- class KeyFieldFilter extends FieldFilter {
4755
- constructor(field, op, value) {
4756
- super(field, op, value);
4757
- this.key = DocumentKey.fromName(value.referenceValue);
4725
+ get key() {
4726
+ throw fail();
4758
4727
  }
4759
- matches(doc) {
4760
- const comparison = DocumentKey.comparator(doc.key, this.key);
4761
- return this.matchesComparison(comparison);
4728
+ get value() {
4729
+ throw fail();
4762
4730
  }
4763
- }
4764
- /** Filter that matches on key fields within an array. */
4765
- class KeyFieldInFilter extends FieldFilter {
4766
- constructor(field, value) {
4767
- super(field, "in" /* IN */, value);
4768
- this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
4731
+ get color() {
4732
+ throw fail();
4769
4733
  }
4770
- matches(doc) {
4771
- return this.keys.some(key => key.isEqual(doc.key));
4734
+ get left() {
4735
+ throw fail();
4772
4736
  }
4773
- }
4774
- /** Filter that matches on key fields not present within an array. */
4775
- class KeyFieldNotInFilter extends FieldFilter {
4776
- constructor(field, value) {
4777
- super(field, "not-in" /* NOT_IN */, value);
4778
- this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
4737
+ get right() {
4738
+ throw fail();
4779
4739
  }
4780
- matches(doc) {
4781
- return !this.keys.some(key => key.isEqual(doc.key));
4740
+ // Returns a copy of the current node.
4741
+ copy(key, value, color, left, right) {
4742
+ return this;
4782
4743
  }
4783
- }
4784
- function extractDocumentKeysFromArrayValue(op, value) {
4785
- var _a;
4786
- return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
4787
- return DocumentKey.fromName(v.referenceValue);
4788
- });
4789
- }
4790
- /** A Filter that implements the array-contains operator. */
4791
- class ArrayContainsFilter extends FieldFilter {
4792
- constructor(field, value) {
4793
- super(field, "array-contains" /* ARRAY_CONTAINS */, value);
4744
+ // Returns a copy of the tree, with the specified key/value added.
4745
+ insert(key, value, comparator) {
4746
+ return new LLRBNode(key, value);
4794
4747
  }
4795
- matches(doc) {
4796
- const other = doc.data.field(this.field);
4797
- return isArray(other) && arrayValueContains(other.arrayValue, this.value);
4748
+ // Returns a copy of the tree, with the specified key removed.
4749
+ remove(key, comparator) {
4750
+ return this;
4798
4751
  }
4799
- }
4800
- /** A Filter that implements the IN operator. */
4801
- class InFilter extends FieldFilter {
4802
- constructor(field, value) {
4803
- super(field, "in" /* IN */, value);
4804
- }
4805
- matches(doc) {
4806
- const other = doc.data.field(this.field);
4807
- return other !== null && arrayValueContains(this.value.arrayValue, other);
4808
- }
4809
- }
4810
- /** A Filter that implements the not-in operator. */
4811
- class NotInFilter extends FieldFilter {
4812
- constructor(field, value) {
4813
- super(field, "not-in" /* NOT_IN */, value);
4814
- }
4815
- matches(doc) {
4816
- if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
4817
- return false;
4818
- }
4819
- const other = doc.data.field(this.field);
4820
- return other !== null && !arrayValueContains(this.value.arrayValue, other);
4821
- }
4822
- }
4823
- /** A Filter that implements the array-contains-any operator. */
4824
- class ArrayContainsAnyFilter extends FieldFilter {
4825
- constructor(field, value) {
4826
- super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
4827
- }
4828
- matches(doc) {
4829
- const other = doc.data.field(this.field);
4830
- if (!isArray(other) || !other.arrayValue.values) {
4831
- return false;
4832
- }
4833
- return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
4752
+ isEmpty() {
4753
+ return true;
4834
4754
  }
4835
- }
4836
- /**
4837
- * Represents a bound of a query.
4838
- *
4839
- * The bound is specified with the given components representing a position and
4840
- * whether it's just before or just after the position (relative to whatever the
4841
- * query order is).
4842
- *
4843
- * The position represents a logical index position for a query. It's a prefix
4844
- * of values for the (potentially implicit) order by clauses of a query.
4845
- *
4846
- * Bound provides a function to determine whether a document comes before or
4847
- * after a bound. This is influenced by whether the position is just before or
4848
- * just after the provided values.
4849
- */
4850
- class Bound {
4851
- constructor(position, inclusive) {
4852
- this.position = position;
4853
- this.inclusive = inclusive;
4755
+ inorderTraversal(action) {
4756
+ return false;
4854
4757
  }
4855
- }
4856
- /**
4857
- * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
4858
- */
4859
- class OrderBy {
4860
- constructor(field, dir = "asc" /* ASCENDING */) {
4861
- this.field = field;
4862
- this.dir = dir;
4758
+ reverseTraversal(action) {
4759
+ return false;
4863
4760
  }
4864
- }
4865
- function canonifyOrderBy(orderBy) {
4866
- // TODO(b/29183165): Make this collision robust.
4867
- return orderBy.field.canonicalString() + orderBy.dir;
4868
- }
4869
- function stringifyOrderBy(orderBy) {
4870
- return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
4871
- }
4872
- function orderByEquals(left, right) {
4873
- return left.dir === right.dir && left.field.isEqual(right.field);
4874
- }
4875
- function boundCompareToDocument(bound, orderBy, doc) {
4876
- let comparison = 0;
4877
- for (let i = 0; i < bound.position.length; i++) {
4878
- const orderByComponent = orderBy[i];
4879
- const component = bound.position[i];
4880
- if (orderByComponent.field.isKeyField()) {
4881
- comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
4882
- }
4883
- else {
4884
- const docValue = doc.data.field(orderByComponent.field);
4885
- comparison = valueCompare(component, docValue);
4886
- }
4887
- if (orderByComponent.dir === "desc" /* DESCENDING */) {
4888
- comparison = comparison * -1;
4889
- }
4890
- if (comparison !== 0) {
4891
- break;
4892
- }
4761
+ minKey() {
4762
+ return null;
4893
4763
  }
4894
- return comparison;
4895
- }
4896
- /**
4897
- * Returns true if a document sorts after a bound using the provided sort
4898
- * order.
4899
- */
4900
- function boundSortsAfterDocument(bound, orderBy, doc) {
4901
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4902
- return bound.inclusive ? comparison >= 0 : comparison > 0;
4903
- }
4904
- /**
4905
- * Returns true if a document sorts before a bound using the provided sort
4906
- * order.
4907
- */
4908
- function boundSortsBeforeDocument(bound, orderBy, doc) {
4909
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4910
- return bound.inclusive ? comparison <= 0 : comparison < 0;
4911
- }
4912
- function boundEquals(left, right) {
4913
- if (left === null) {
4914
- return right === null;
4764
+ maxKey() {
4765
+ return null;
4915
4766
  }
4916
- else if (right === null) {
4767
+ isRed() {
4917
4768
  return false;
4918
4769
  }
4919
- if (left.inclusive !== right.inclusive ||
4920
- left.position.length !== right.position.length) {
4921
- return false;
4770
+ // For testing.
4771
+ checkMaxDepth() {
4772
+ return true;
4922
4773
  }
4923
- for (let i = 0; i < left.position.length; i++) {
4924
- const leftPosition = left.position[i];
4925
- const rightPosition = right.position[i];
4926
- if (!valueEquals(leftPosition, rightPosition)) {
4927
- return false;
4928
- }
4774
+ check() {
4775
+ return 0;
4929
4776
  }
4930
- return true;
4931
- }
4777
+ } // end LLRBEmptyNode
4778
+ LLRBNode.EMPTY = new LLRBEmptyNode();
4932
4779
 
4933
4780
  /**
4934
4781
  * @license
@@ -4947,325 +4794,223 @@ function boundEquals(left, right) {
4947
4794
  * limitations under the License.
4948
4795
  */
4949
4796
  /**
4950
- * Query encapsulates all the query attributes we support in the SDK. It can
4951
- * be run against the LocalStore, as well as be converted to a `Target` to
4952
- * query the RemoteStore results.
4797
+ * SortedSet is an immutable (copy-on-write) collection that holds elements
4798
+ * in order specified by the provided comparator.
4953
4799
  *
4954
- * Visible for testing.
4800
+ * NOTE: if provided comparator returns 0 for two elements, we consider them to
4801
+ * be equal!
4955
4802
  */
4956
- class QueryImpl {
4957
- /**
4958
- * Initializes a Query with a path and optional additional query constraints.
4959
- * Path must currently be empty if this is a collection group query.
4960
- */
4961
- constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
4962
- this.path = path;
4963
- this.collectionGroup = collectionGroup;
4964
- this.explicitOrderBy = explicitOrderBy;
4965
- this.filters = filters;
4966
- this.limit = limit;
4967
- this.limitType = limitType;
4968
- this.startAt = startAt;
4969
- this.endAt = endAt;
4970
- this.memoizedOrderBy = null;
4971
- // The corresponding `Target` of this `Query` instance.
4972
- this.memoizedTarget = null;
4973
- if (this.startAt) ;
4974
- if (this.endAt) ;
4803
+ class SortedSet {
4804
+ constructor(comparator) {
4805
+ this.comparator = comparator;
4806
+ this.data = new SortedMap(this.comparator);
4975
4807
  }
4976
- }
4977
- /** Creates a new Query instance with the options provided. */
4978
- function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
4979
- return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
4980
- }
4981
- /** Creates a new Query for a query that matches all documents at `path` */
4982
- function newQueryForPath(path) {
4983
- return new QueryImpl(path);
4984
- }
4985
- /**
4986
- * Helper to convert a collection group query into a collection query at a
4987
- * specific path. This is used when executing collection group queries, since
4988
- * we have to split the query into a set of collection queries at multiple
4989
- * paths.
4990
- */
4991
- function asCollectionQueryAtPath(query, path) {
4992
- return new QueryImpl(path,
4993
- /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
4994
- }
4995
- /**
4996
- * Returns true if this query does not specify any query constraints that
4997
- * could remove results.
4998
- */
4999
- function matchesAllDocuments(query) {
5000
- return (query.filters.length === 0 &&
5001
- query.limit === null &&
5002
- query.startAt == null &&
5003
- query.endAt == null &&
5004
- (query.explicitOrderBy.length === 0 ||
5005
- (query.explicitOrderBy.length === 1 &&
5006
- query.explicitOrderBy[0].field.isKeyField())));
5007
- }
5008
- function hasLimitToFirst(query) {
5009
- return !isNullOrUndefined(query.limit) && query.limitType === "F" /* First */;
5010
- }
5011
- function hasLimitToLast(query) {
5012
- return !isNullOrUndefined(query.limit) && query.limitType === "L" /* Last */;
5013
- }
5014
- function getFirstOrderByField(query) {
5015
- return query.explicitOrderBy.length > 0
5016
- ? query.explicitOrderBy[0].field
5017
- : null;
5018
- }
5019
- function getInequalityFilterField(query) {
5020
- for (const filter of query.filters) {
5021
- if (filter.isInequality()) {
5022
- return filter.field;
5023
- }
4808
+ has(elem) {
4809
+ return this.data.get(elem) !== null;
5024
4810
  }
5025
- return null;
5026
- }
5027
- /**
5028
- * Checks if any of the provided Operators are included in the query and
5029
- * returns the first one that is, or null if none are.
5030
- */
5031
- function findFilterOperator(query, operators) {
5032
- for (const filter of query.filters) {
5033
- if (operators.indexOf(filter.op) >= 0) {
5034
- return filter.op;
4811
+ first() {
4812
+ return this.data.minKey();
4813
+ }
4814
+ last() {
4815
+ return this.data.maxKey();
4816
+ }
4817
+ get size() {
4818
+ return this.data.size;
4819
+ }
4820
+ indexOf(elem) {
4821
+ return this.data.indexOf(elem);
4822
+ }
4823
+ /** Iterates elements in order defined by "comparator" */
4824
+ forEach(cb) {
4825
+ this.data.inorderTraversal((k, v) => {
4826
+ cb(k);
4827
+ return false;
4828
+ });
4829
+ }
4830
+ /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
4831
+ forEachInRange(range, cb) {
4832
+ const iter = this.data.getIteratorFrom(range[0]);
4833
+ while (iter.hasNext()) {
4834
+ const elem = iter.getNext();
4835
+ if (this.comparator(elem.key, range[1]) >= 0) {
4836
+ return;
4837
+ }
4838
+ cb(elem.key);
5035
4839
  }
5036
4840
  }
5037
- return null;
5038
- }
5039
- /**
5040
- * Creates a new Query for a collection group query that matches all documents
5041
- * within the provided collection group.
5042
- */
5043
- function newQueryForCollectionGroup(collectionId) {
5044
- return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5045
- }
5046
- /**
5047
- * Returns whether the query matches a single document by path (rather than a
5048
- * collection).
5049
- */
5050
- function isDocumentQuery$1(query) {
5051
- return (DocumentKey.isDocumentKey(query.path) &&
5052
- query.collectionGroup === null &&
5053
- query.filters.length === 0);
5054
- }
5055
- /**
5056
- * Returns whether the query matches a collection group rather than a specific
5057
- * collection.
5058
- */
5059
- function isCollectionGroupQuery(query) {
5060
- return query.collectionGroup !== null;
5061
- }
5062
- /**
5063
- * Returns the implicit order by constraint that is used to execute the Query,
5064
- * which can be different from the order by constraints the user provided (e.g.
5065
- * the SDK and backend always orders by `__name__`).
5066
- */
5067
- function queryOrderBy(query) {
5068
- const queryImpl = debugCast(query);
5069
- if (queryImpl.memoizedOrderBy === null) {
5070
- queryImpl.memoizedOrderBy = [];
5071
- const inequalityField = getInequalityFilterField(queryImpl);
5072
- const firstOrderByField = getFirstOrderByField(queryImpl);
5073
- if (inequalityField !== null && firstOrderByField === null) {
5074
- // In order to implicitly add key ordering, we must also add the
5075
- // inequality filter field for it to be a valid query.
5076
- // Note that the default inequality field and key ordering is ascending.
5077
- if (!inequalityField.isKeyField()) {
5078
- queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5079
- }
5080
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
4841
+ /**
4842
+ * Iterates over `elem`s such that: start &lt;= elem until false is returned.
4843
+ */
4844
+ forEachWhile(cb, start) {
4845
+ let iter;
4846
+ if (start !== undefined) {
4847
+ iter = this.data.getIteratorFrom(start);
5081
4848
  }
5082
4849
  else {
5083
- let foundKeyOrdering = false;
5084
- for (const orderBy of queryImpl.explicitOrderBy) {
5085
- queryImpl.memoizedOrderBy.push(orderBy);
5086
- if (orderBy.field.isKeyField()) {
5087
- foundKeyOrdering = true;
5088
- }
5089
- }
5090
- if (!foundKeyOrdering) {
5091
- // The order of the implicit key ordering always matches the last
5092
- // explicit order by
5093
- const lastDirection = queryImpl.explicitOrderBy.length > 0
5094
- ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5095
- .dir
5096
- : "asc" /* ASCENDING */;
5097
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
5098
- }
5099
- }
5100
- }
5101
- return queryImpl.memoizedOrderBy;
5102
- }
5103
- /**
5104
- * Converts this `Query` instance to it's corresponding `Target` representation.
5105
- */
5106
- function queryToTarget(query) {
5107
- const queryImpl = debugCast(query);
5108
- if (!queryImpl.memoizedTarget) {
5109
- if (queryImpl.limitType === "F" /* First */) {
5110
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
4850
+ iter = this.data.getIterator();
5111
4851
  }
5112
- else {
5113
- // Flip the orderBy directions since we want the last results
5114
- const orderBys = [];
5115
- for (const orderBy of queryOrderBy(queryImpl)) {
5116
- const dir = orderBy.dir === "desc" /* DESCENDING */
5117
- ? "asc" /* ASCENDING */
5118
- : "desc" /* DESCENDING */;
5119
- orderBys.push(new OrderBy(orderBy.field, dir));
4852
+ while (iter.hasNext()) {
4853
+ const elem = iter.getNext();
4854
+ const result = cb(elem.key);
4855
+ if (!result) {
4856
+ return;
5120
4857
  }
5121
- // We need to swap the cursors to match the now-flipped query ordering.
5122
- const startAt = queryImpl.endAt
5123
- ? new Bound(queryImpl.endAt.position, !queryImpl.endAt.inclusive)
5124
- : null;
5125
- const endAt = queryImpl.startAt
5126
- ? new Bound(queryImpl.startAt.position, !queryImpl.startAt.inclusive)
5127
- : null;
5128
- // Now return as a LimitType.First query.
5129
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5130
4858
  }
5131
4859
  }
5132
- return queryImpl.memoizedTarget;
5133
- }
5134
- function queryWithAddedFilter(query, filter) {
5135
- const newFilters = query.filters.concat([filter]);
5136
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5137
- }
5138
- function queryWithAddedOrderBy(query, orderBy) {
5139
- // TODO(dimond): validate that orderBy does not list the same key twice.
5140
- const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5141
- return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5142
- }
5143
- function queryWithLimit(query, limit, limitType) {
5144
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5145
- }
5146
- function queryWithStartAt(query, bound) {
5147
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5148
- }
5149
- function queryWithEndAt(query, bound) {
5150
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5151
- }
5152
- function queryEquals(left, right) {
5153
- return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5154
- left.limitType === right.limitType);
5155
- }
5156
- // TODO(b/29183165): This is used to get a unique string from a query to, for
5157
- // example, use as a dictionary key, but the implementation is subject to
5158
- // collisions. Make it collision-free.
5159
- function canonifyQuery(query) {
5160
- return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5161
- }
5162
- function stringifyQuery(query) {
5163
- return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5164
- }
5165
- /** Returns whether `doc` matches the constraints of `query`. */
5166
- function queryMatches(query, doc) {
5167
- return (doc.isFoundDocument() &&
5168
- queryMatchesPathAndCollectionGroup(query, doc) &&
5169
- queryMatchesOrderBy(query, doc) &&
5170
- queryMatchesFilters(query, doc) &&
5171
- queryMatchesBounds(query, doc));
5172
- }
5173
- function queryMatchesPathAndCollectionGroup(query, doc) {
5174
- const docPath = doc.key.path;
5175
- if (query.collectionGroup !== null) {
5176
- // NOTE: this.path is currently always empty since we don't expose Collection
5177
- // Group queries rooted at a document path yet.
5178
- return (doc.key.hasCollectionId(query.collectionGroup) &&
5179
- query.path.isPrefixOf(docPath));
4860
+ /** Finds the least element greater than or equal to `elem`. */
4861
+ firstAfterOrEqual(elem) {
4862
+ const iter = this.data.getIteratorFrom(elem);
4863
+ return iter.hasNext() ? iter.getNext().key : null;
5180
4864
  }
5181
- else if (DocumentKey.isDocumentKey(query.path)) {
5182
- // exact match for document queries
5183
- return query.path.isEqual(docPath);
4865
+ getIterator() {
4866
+ return new SortedSetIterator(this.data.getIterator());
5184
4867
  }
5185
- else {
5186
- // shallow ancestor queries by default
5187
- return query.path.isImmediateParentOf(docPath);
4868
+ getIteratorFrom(key) {
4869
+ return new SortedSetIterator(this.data.getIteratorFrom(key));
5188
4870
  }
5189
- }
5190
- /**
5191
- * A document must have a value for every ordering clause in order to show up
5192
- * in the results.
5193
- */
5194
- function queryMatchesOrderBy(query, doc) {
5195
- for (const orderBy of query.explicitOrderBy) {
5196
- // order by key always matches
5197
- if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5198
- return false;
4871
+ /** Inserts or updates an element */
4872
+ add(elem) {
4873
+ return this.copy(this.data.remove(elem).insert(elem, true));
4874
+ }
4875
+ /** Deletes an element */
4876
+ delete(elem) {
4877
+ if (!this.has(elem)) {
4878
+ return this;
5199
4879
  }
4880
+ return this.copy(this.data.remove(elem));
5200
4881
  }
5201
- return true;
5202
- }
5203
- function queryMatchesFilters(query, doc) {
5204
- for (const filter of query.filters) {
5205
- if (!filter.matches(doc)) {
4882
+ isEmpty() {
4883
+ return this.data.isEmpty();
4884
+ }
4885
+ unionWith(other) {
4886
+ let result = this;
4887
+ // Make sure `result` always refers to the larger one of the two sets.
4888
+ if (result.size < other.size) {
4889
+ result = other;
4890
+ other = this;
4891
+ }
4892
+ other.forEach(elem => {
4893
+ result = result.add(elem);
4894
+ });
4895
+ return result;
4896
+ }
4897
+ isEqual(other) {
4898
+ if (!(other instanceof SortedSet)) {
4899
+ return false;
4900
+ }
4901
+ if (this.size !== other.size) {
5206
4902
  return false;
5207
4903
  }
4904
+ const thisIt = this.data.getIterator();
4905
+ const otherIt = other.data.getIterator();
4906
+ while (thisIt.hasNext()) {
4907
+ const thisElem = thisIt.getNext().key;
4908
+ const otherElem = otherIt.getNext().key;
4909
+ if (this.comparator(thisElem, otherElem) !== 0) {
4910
+ return false;
4911
+ }
4912
+ }
4913
+ return true;
4914
+ }
4915
+ toArray() {
4916
+ const res = [];
4917
+ this.forEach(targetId => {
4918
+ res.push(targetId);
4919
+ });
4920
+ return res;
4921
+ }
4922
+ toString() {
4923
+ const result = [];
4924
+ this.forEach(elem => result.push(elem));
4925
+ return 'SortedSet(' + result.toString() + ')';
4926
+ }
4927
+ copy(data) {
4928
+ const result = new SortedSet(this.comparator);
4929
+ result.data = data;
4930
+ return result;
5208
4931
  }
5209
- return true;
5210
4932
  }
5211
- /** Makes sure a document is within the bounds, if provided. */
5212
- function queryMatchesBounds(query, doc) {
5213
- if (query.startAt &&
5214
- !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5215
- return false;
4933
+ class SortedSetIterator {
4934
+ constructor(iter) {
4935
+ this.iter = iter;
5216
4936
  }
5217
- if (query.endAt &&
5218
- !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5219
- return false;
4937
+ getNext() {
4938
+ return this.iter.getNext().key;
4939
+ }
4940
+ hasNext() {
4941
+ return this.iter.hasNext();
5220
4942
  }
5221
- return true;
5222
4943
  }
5223
4944
  /**
5224
- * Returns the collection group that this query targets.
4945
+ * Compares two sorted sets for equality using their natural ordering. The
4946
+ * method computes the intersection and invokes `onAdd` for every element that
4947
+ * is in `after` but not `before`. `onRemove` is invoked for every element in
4948
+ * `before` but missing from `after`.
5225
4949
  *
5226
- * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5227
- * synchronization for query results.
5228
- */
5229
- function queryCollectionGroup(query) {
5230
- return (query.collectionGroup ||
5231
- (query.path.length % 2 === 1
5232
- ? query.path.lastSegment()
5233
- : query.path.get(query.path.length - 2)));
5234
- }
5235
- /**
5236
- * Returns a new comparator function that can be used to compare two documents
5237
- * based on the Query's ordering constraint.
4950
+ * The method creates a copy of both `before` and `after` and runs in O(n log
4951
+ * n), where n is the size of the two lists.
4952
+ *
4953
+ * @param before - The elements that exist in the original set.
4954
+ * @param after - The elements to diff against the original set.
4955
+ * @param comparator - The comparator for the elements in before and after.
4956
+ * @param onAdd - A function to invoke for every element that is part of `
4957
+ * after` but not `before`.
4958
+ * @param onRemove - A function to invoke for every element that is part of
4959
+ * `before` but not `after`.
5238
4960
  */
5239
- function newQueryComparator(query) {
5240
- return (d1, d2) => {
5241
- let comparedOnKeyField = false;
5242
- for (const orderBy of queryOrderBy(query)) {
5243
- const comp = compareDocs(orderBy, d1, d2);
5244
- if (comp !== 0) {
5245
- return comp;
4961
+ function diffSortedSets(before, after, comparator, onAdd, onRemove) {
4962
+ const beforeIt = before.getIterator();
4963
+ const afterIt = after.getIterator();
4964
+ let beforeValue = advanceIterator(beforeIt);
4965
+ let afterValue = advanceIterator(afterIt);
4966
+ // Walk through the two sets at the same time, using the ordering defined by
4967
+ // `comparator`.
4968
+ while (beforeValue || afterValue) {
4969
+ let added = false;
4970
+ let removed = false;
4971
+ if (beforeValue && afterValue) {
4972
+ const cmp = comparator(beforeValue, afterValue);
4973
+ if (cmp < 0) {
4974
+ // The element was removed if the next element in our ordered
4975
+ // walkthrough is only in `before`.
4976
+ removed = true;
4977
+ }
4978
+ else if (cmp > 0) {
4979
+ // The element was added if the next element in our ordered walkthrough
4980
+ // is only in `after`.
4981
+ added = true;
5246
4982
  }
5247
- comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
5248
4983
  }
5249
- return 0;
5250
- };
5251
- }
5252
- function compareDocs(orderBy, d1, d2) {
5253
- const comparison = orderBy.field.isKeyField()
5254
- ? DocumentKey.comparator(d1.key, d2.key)
5255
- : compareDocumentsByField(orderBy.field, d1, d2);
5256
- switch (orderBy.dir) {
5257
- case "asc" /* ASCENDING */:
5258
- return comparison;
5259
- case "desc" /* DESCENDING */:
5260
- return -1 * comparison;
5261
- default:
5262
- return fail();
4984
+ else if (beforeValue != null) {
4985
+ removed = true;
4986
+ }
4987
+ else {
4988
+ added = true;
4989
+ }
4990
+ if (added) {
4991
+ onAdd(afterValue);
4992
+ afterValue = advanceIterator(afterIt);
4993
+ }
4994
+ else if (removed) {
4995
+ onRemove(beforeValue);
4996
+ beforeValue = advanceIterator(beforeIt);
4997
+ }
4998
+ else {
4999
+ beforeValue = advanceIterator(beforeIt);
5000
+ afterValue = advanceIterator(afterIt);
5001
+ }
5263
5002
  }
5003
+ }
5004
+ /**
5005
+ * Returns the next element from the iterator or `undefined` if none available.
5006
+ */
5007
+ function advanceIterator(it) {
5008
+ return it.hasNext() ? it.getNext() : undefined;
5264
5009
  }
5265
5010
 
5266
5011
  /**
5267
5012
  * @license
5268
- * Copyright 2017 Google LLC
5013
+ * Copyright 2019 Google LLC
5269
5014
  *
5270
5015
  * Licensed under the Apache License, Version 2.0 (the "License");
5271
5016
  * you may not use this file except in compliance with the License.
@@ -5279,555 +5024,961 @@ function compareDocs(orderBy, d1, d2) {
5279
5024
  * See the License for the specific language governing permissions and
5280
5025
  * limitations under the License.
5281
5026
  */
5027
+ // Visible for testing
5028
+ class TargetImpl {
5029
+ constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5030
+ this.path = path;
5031
+ this.collectionGroup = collectionGroup;
5032
+ this.orderBy = orderBy;
5033
+ this.filters = filters;
5034
+ this.limit = limit;
5035
+ this.startAt = startAt;
5036
+ this.endAt = endAt;
5037
+ this.memoizedCanonicalId = null;
5038
+ }
5039
+ }
5282
5040
  /**
5283
- * A map implementation that uses objects as keys. Objects must have an
5284
- * associated equals function and must be immutable. Entries in the map are
5285
- * stored together with the key being produced from the mapKeyFn. This map
5286
- * automatically handles collisions of keys.
5041
+ * Initializes a Target with a path and optional additional query constraints.
5042
+ * Path must currently be empty if this is a collection group query.
5043
+ *
5044
+ * NOTE: you should always construct `Target` from `Query.toTarget` instead of
5045
+ * using this factory method, because `Query` provides an implicit `orderBy`
5046
+ * property.
5287
5047
  */
5288
- class ObjectMap {
5289
- constructor(mapKeyFn, equalsFn) {
5290
- this.mapKeyFn = mapKeyFn;
5291
- this.equalsFn = equalsFn;
5292
- /**
5293
- * The inner map for a key/value pair. Due to the possibility of collisions we
5294
- * keep a list of entries that we do a linear search through to find an actual
5295
- * match. Note that collisions should be rare, so we still expect near
5296
- * constant time lookups in practice.
5297
- */
5298
- this.inner = {};
5299
- /** The number of entries stored in the map */
5300
- this.innerSize = 0;
5301
- }
5302
- /** Get a value for this key, or undefined if it does not exist. */
5303
- get(key) {
5304
- const id = this.mapKeyFn(key);
5305
- const matches = this.inner[id];
5306
- if (matches === undefined) {
5307
- return undefined;
5048
+ function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5049
+ return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
5050
+ }
5051
+ function canonifyTarget(target) {
5052
+ const targetImpl = debugCast(target);
5053
+ if (targetImpl.memoizedCanonicalId === null) {
5054
+ let str = targetImpl.path.canonicalString();
5055
+ if (targetImpl.collectionGroup !== null) {
5056
+ str += '|cg:' + targetImpl.collectionGroup;
5308
5057
  }
5309
- for (const [otherKey, value] of matches) {
5310
- if (this.equalsFn(otherKey, key)) {
5311
- return value;
5312
- }
5058
+ str += '|f:';
5059
+ str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
5060
+ str += '|ob:';
5061
+ str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
5062
+ if (!isNullOrUndefined(targetImpl.limit)) {
5063
+ str += '|l:';
5064
+ str += targetImpl.limit;
5313
5065
  }
5314
- return undefined;
5315
- }
5316
- has(key) {
5317
- return this.get(key) !== undefined;
5318
- }
5319
- /** Put this key and value in the map. */
5320
- set(key, value) {
5321
- const id = this.mapKeyFn(key);
5322
- const matches = this.inner[id];
5323
- if (matches === undefined) {
5324
- this.inner[id] = [[key, value]];
5325
- this.innerSize++;
5326
- return;
5066
+ if (targetImpl.startAt) {
5067
+ str += '|lb:';
5068
+ str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
5069
+ str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
5327
5070
  }
5328
- for (let i = 0; i < matches.length; i++) {
5329
- if (this.equalsFn(matches[i][0], key)) {
5330
- // This is updating an existing entry and does not increase `innerSize`.
5331
- matches[i] = [key, value];
5332
- return;
5333
- }
5071
+ if (targetImpl.endAt) {
5072
+ str += '|ub:';
5073
+ str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
5074
+ str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
5334
5075
  }
5335
- matches.push([key, value]);
5336
- this.innerSize++;
5076
+ targetImpl.memoizedCanonicalId = str;
5337
5077
  }
5338
- /**
5339
- * Remove this key from the map. Returns a boolean if anything was deleted.
5340
- */
5341
- delete(key) {
5342
- const id = this.mapKeyFn(key);
5343
- const matches = this.inner[id];
5344
- if (matches === undefined) {
5078
+ return targetImpl.memoizedCanonicalId;
5079
+ }
5080
+ function stringifyTarget(target) {
5081
+ let str = target.path.canonicalString();
5082
+ if (target.collectionGroup !== null) {
5083
+ str += ' collectionGroup=' + target.collectionGroup;
5084
+ }
5085
+ if (target.filters.length > 0) {
5086
+ str += `, filters: [${target.filters
5087
+ .map(f => stringifyFilter(f))
5088
+ .join(', ')}]`;
5089
+ }
5090
+ if (!isNullOrUndefined(target.limit)) {
5091
+ str += ', limit: ' + target.limit;
5092
+ }
5093
+ if (target.orderBy.length > 0) {
5094
+ str += `, orderBy: [${target.orderBy
5095
+ .map(o => stringifyOrderBy(o))
5096
+ .join(', ')}]`;
5097
+ }
5098
+ if (target.startAt) {
5099
+ str += ', startAt: ';
5100
+ str += target.startAt.inclusive ? 'b:' : 'a:';
5101
+ str += target.startAt.position.map(p => canonicalId(p)).join(',');
5102
+ }
5103
+ if (target.endAt) {
5104
+ str += ', endAt: ';
5105
+ str += target.endAt.inclusive ? 'a:' : 'b:';
5106
+ str += target.endAt.position.map(p => canonicalId(p)).join(',');
5107
+ }
5108
+ return `Target(${str})`;
5109
+ }
5110
+ function targetEquals(left, right) {
5111
+ if (left.limit !== right.limit) {
5112
+ return false;
5113
+ }
5114
+ if (left.orderBy.length !== right.orderBy.length) {
5115
+ return false;
5116
+ }
5117
+ for (let i = 0; i < left.orderBy.length; i++) {
5118
+ if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
5345
5119
  return false;
5346
5120
  }
5347
- for (let i = 0; i < matches.length; i++) {
5348
- if (this.equalsFn(matches[i][0], key)) {
5349
- if (matches.length === 1) {
5350
- delete this.inner[id];
5351
- }
5352
- else {
5353
- matches.splice(i, 1);
5354
- }
5355
- this.innerSize--;
5356
- return true;
5357
- }
5358
- }
5121
+ }
5122
+ if (left.filters.length !== right.filters.length) {
5359
5123
  return false;
5360
5124
  }
5361
- forEach(fn) {
5362
- forEach(this.inner, (_, entries) => {
5363
- for (const [k, v] of entries) {
5364
- fn(k, v);
5365
- }
5366
- });
5125
+ for (let i = 0; i < left.filters.length; i++) {
5126
+ if (!filterEquals(left.filters[i], right.filters[i])) {
5127
+ return false;
5128
+ }
5367
5129
  }
5368
- isEmpty() {
5369
- return isEmpty(this.inner);
5130
+ if (left.collectionGroup !== right.collectionGroup) {
5131
+ return false;
5370
5132
  }
5371
- size() {
5372
- return this.innerSize;
5133
+ if (!left.path.isEqual(right.path)) {
5134
+ return false;
5373
5135
  }
5374
- }
5375
-
5136
+ if (!boundEquals(left.startAt, right.startAt)) {
5137
+ return false;
5138
+ }
5139
+ return boundEquals(left.endAt, right.endAt);
5140
+ }
5141
+ function targetIsDocumentTarget(target) {
5142
+ return (DocumentKey.isDocumentKey(target.path) &&
5143
+ target.collectionGroup === null &&
5144
+ target.filters.length === 0);
5145
+ }
5146
+ /** Returns the field filters that target the given field path. */
5147
+ function targetGetFieldFiltersForPath(target, path) {
5148
+ return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
5149
+ }
5376
5150
  /**
5377
- * @license
5378
- * Copyright 2017 Google LLC
5379
- *
5380
- * Licensed under the Apache License, Version 2.0 (the "License");
5381
- * you may not use this file except in compliance with the License.
5382
- * You may obtain a copy of the License at
5383
- *
5384
- * http://www.apache.org/licenses/LICENSE-2.0
5385
- *
5386
- * Unless required by applicable law or agreed to in writing, software
5387
- * distributed under the License is distributed on an "AS IS" BASIS,
5388
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5389
- * See the License for the specific language governing permissions and
5390
- * limitations under the License.
5151
+ * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
5152
+ * filters. Returns `null` if there are no such filters.
5391
5153
  */
5392
- // An immutable sorted map implementation, based on a Left-leaning Red-Black
5393
- // tree.
5394
- class SortedMap {
5395
- constructor(comparator, root) {
5396
- this.comparator = comparator;
5397
- this.root = root ? root : LLRBNode.EMPTY;
5398
- }
5399
- // Returns a copy of the map, with the specified key/value added or replaced.
5400
- insert(key, value) {
5401
- return new SortedMap(this.comparator, this.root
5402
- .insert(key, value, this.comparator)
5403
- .copy(null, null, LLRBNode.BLACK, null, null));
5404
- }
5405
- // Returns a copy of the map, with the specified key removed.
5406
- remove(key) {
5407
- return new SortedMap(this.comparator, this.root
5408
- .remove(key, this.comparator)
5409
- .copy(null, null, LLRBNode.BLACK, null, null));
5154
+ function targetGetArrayValues(target, fieldIndex) {
5155
+ const segment = fieldIndexGetArraySegment(fieldIndex);
5156
+ if (segment === undefined) {
5157
+ return null;
5410
5158
  }
5411
- // Returns the value of the node with the given key, or null.
5412
- get(key) {
5413
- let node = this.root;
5414
- while (!node.isEmpty()) {
5415
- const cmp = this.comparator(key, node.key);
5416
- if (cmp === 0) {
5417
- return node.value;
5418
- }
5419
- else if (cmp < 0) {
5420
- node = node.left;
5421
- }
5422
- else if (cmp > 0) {
5423
- node = node.right;
5424
- }
5159
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5160
+ switch (fieldFilter.op) {
5161
+ case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
5162
+ return fieldFilter.value.arrayValue.values || [];
5163
+ case "array-contains" /* ARRAY_CONTAINS */:
5164
+ return [fieldFilter.value];
5165
+ // Remaining filters are not array filters.
5425
5166
  }
5426
- return null;
5427
5167
  }
5428
- // Returns the index of the element in this sorted map, or -1 if it doesn't
5429
- // exist.
5430
- indexOf(key) {
5431
- // Number of nodes that were pruned when descending right
5432
- let prunedNodes = 0;
5433
- let node = this.root;
5434
- while (!node.isEmpty()) {
5435
- const cmp = this.comparator(key, node.key);
5436
- if (cmp === 0) {
5437
- return prunedNodes + node.left.size;
5438
- }
5439
- else if (cmp < 0) {
5440
- node = node.left;
5441
- }
5442
- else {
5443
- // Count all nodes left of the node plus the node itself
5444
- prunedNodes += node.left.size + 1;
5445
- node = node.right;
5168
+ return null;
5169
+ }
5170
+ /**
5171
+ * Returns the list of values that are used in != or NOT_IN filters. Returns
5172
+ * `null` if there are no such filters.
5173
+ */
5174
+ function targetGetNotInValues(target, fieldIndex) {
5175
+ const values = new Map();
5176
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5177
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5178
+ switch (fieldFilter.op) {
5179
+ case "==" /* EQUAL */:
5180
+ case "in" /* IN */:
5181
+ // Encode equality prefix, which is encoded in the index value before
5182
+ // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
5183
+ // `value != 'ab'`).
5184
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5185
+ break;
5186
+ case "not-in" /* NOT_IN */:
5187
+ case "!=" /* NOT_EQUAL */:
5188
+ // NotIn/NotEqual is always a suffix. There cannot be any remaining
5189
+ // segments and hence we can return early here.
5190
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5191
+ return Array.from(values.values());
5192
+ // Remaining filters cannot be used as notIn bounds.
5446
5193
  }
5447
5194
  }
5448
- // Node not found
5449
- return -1;
5450
- }
5451
- isEmpty() {
5452
- return this.root.isEmpty();
5453
- }
5454
- // Returns the total number of nodes in the map.
5455
- get size() {
5456
- return this.root.size;
5457
5195
  }
5458
- // Returns the minimum key in the map.
5459
- minKey() {
5460
- return this.root.minKey();
5461
- }
5462
- // Returns the maximum key in the map.
5463
- maxKey() {
5464
- return this.root.maxKey();
5196
+ return null;
5197
+ }
5198
+ /**
5199
+ * Returns a lower bound of field values that can be used as a starting point to
5200
+ * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
5201
+ * exists.
5202
+ */
5203
+ function targetGetLowerBound(target, fieldIndex) {
5204
+ const values = [];
5205
+ let inclusive = true;
5206
+ // For each segment, retrieve a lower bound if there is a suitable filter or
5207
+ // startAt.
5208
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5209
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5210
+ ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)
5211
+ : targetGetDescendingBound(target, segment.fieldPath, target.startAt);
5212
+ values.push(segmentBound.value);
5213
+ inclusive && (inclusive = segmentBound.inclusive);
5465
5214
  }
5466
- // Traverses the map in key order and calls the specified action function
5467
- // for each key/value pair. If action returns true, traversal is aborted.
5468
- // Returns the first truthy value returned by action, or the last falsey
5469
- // value returned by action.
5470
- inorderTraversal(action) {
5471
- return this.root.inorderTraversal(action);
5215
+ return new Bound(values, inclusive);
5216
+ }
5217
+ /**
5218
+ * Returns an upper bound of field values that can be used as an ending point
5219
+ * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
5220
+ * upper bound exists.
5221
+ */
5222
+ function targetGetUpperBound(target, fieldIndex) {
5223
+ const values = [];
5224
+ let inclusive = true;
5225
+ // For each segment, retrieve an upper bound if there is a suitable filter or
5226
+ // endAt.
5227
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5228
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5229
+ ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)
5230
+ : targetGetAscendingBound(target, segment.fieldPath, target.endAt);
5231
+ values.push(segmentBound.value);
5232
+ inclusive && (inclusive = segmentBound.inclusive);
5472
5233
  }
5473
- forEach(fn) {
5474
- this.inorderTraversal((k, v) => {
5475
- fn(k, v);
5476
- return false;
5477
- });
5234
+ return new Bound(values, inclusive);
5235
+ }
5236
+ /**
5237
+ * Returns the value to use as the lower bound for ascending index segment at
5238
+ * the provided `fieldPath` (or the upper bound for an descending segment).
5239
+ */
5240
+ function targetGetAscendingBound(target, fieldPath, bound) {
5241
+ let value = MIN_VALUE;
5242
+ let inclusive = true;
5243
+ // Process all filters to find a value for the current field segment
5244
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5245
+ let filterValue = MIN_VALUE;
5246
+ let filterInclusive = true;
5247
+ switch (fieldFilter.op) {
5248
+ case "<" /* LESS_THAN */:
5249
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5250
+ filterValue = valuesGetLowerBound(fieldFilter.value);
5251
+ break;
5252
+ case "==" /* EQUAL */:
5253
+ case "in" /* IN */:
5254
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5255
+ filterValue = fieldFilter.value;
5256
+ break;
5257
+ case ">" /* GREATER_THAN */:
5258
+ filterValue = fieldFilter.value;
5259
+ filterInclusive = false;
5260
+ break;
5261
+ case "!=" /* NOT_EQUAL */:
5262
+ case "not-in" /* NOT_IN */:
5263
+ filterValue = MIN_VALUE;
5264
+ break;
5265
+ // Remaining filters cannot be used as lower bounds.
5266
+ }
5267
+ if (lowerBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) < 0) {
5268
+ value = filterValue;
5269
+ inclusive = filterInclusive;
5270
+ }
5478
5271
  }
5479
- toString() {
5480
- const descriptions = [];
5481
- this.inorderTraversal((k, v) => {
5482
- descriptions.push(`${k}:${v}`);
5483
- return false;
5484
- });
5485
- return `{${descriptions.join(', ')}}`;
5272
+ // If there is an additional bound, compare the values against the existing
5273
+ // range to see if we can narrow the scope.
5274
+ if (bound !== null) {
5275
+ for (let i = 0; i < target.orderBy.length; ++i) {
5276
+ const orderBy = target.orderBy[i];
5277
+ if (orderBy.field.isEqual(fieldPath)) {
5278
+ const cursorValue = bound.position[i];
5279
+ if (lowerBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) < 0) {
5280
+ value = cursorValue;
5281
+ inclusive = bound.inclusive;
5282
+ }
5283
+ break;
5284
+ }
5285
+ }
5486
5286
  }
5487
- // Traverses the map in reverse key order and calls the specified action
5488
- // function for each key/value pair. If action returns true, traversal is
5489
- // aborted.
5490
- // Returns the first truthy value returned by action, or the last falsey
5491
- // value returned by action.
5492
- reverseTraversal(action) {
5493
- return this.root.reverseTraversal(action);
5287
+ return { value, inclusive };
5288
+ }
5289
+ /**
5290
+ * Returns the value to use as the upper bound for ascending index segment at
5291
+ * the provided `fieldPath` (or the lower bound for a descending segment).
5292
+ */
5293
+ function targetGetDescendingBound(target, fieldPath, bound) {
5294
+ let value = MAX_VALUE;
5295
+ let inclusive = true;
5296
+ // Process all filters to find a value for the current field segment
5297
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5298
+ let filterValue = MAX_VALUE;
5299
+ let filterInclusive = true;
5300
+ switch (fieldFilter.op) {
5301
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5302
+ case ">" /* GREATER_THAN */:
5303
+ filterValue = valuesGetUpperBound(fieldFilter.value);
5304
+ filterInclusive = false;
5305
+ break;
5306
+ case "==" /* EQUAL */:
5307
+ case "in" /* IN */:
5308
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5309
+ filterValue = fieldFilter.value;
5310
+ break;
5311
+ case "<" /* LESS_THAN */:
5312
+ filterValue = fieldFilter.value;
5313
+ filterInclusive = false;
5314
+ break;
5315
+ case "!=" /* NOT_EQUAL */:
5316
+ case "not-in" /* NOT_IN */:
5317
+ filterValue = MAX_VALUE;
5318
+ break;
5319
+ // Remaining filters cannot be used as upper bounds.
5320
+ }
5321
+ if (upperBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) > 0) {
5322
+ value = filterValue;
5323
+ inclusive = filterInclusive;
5324
+ }
5494
5325
  }
5495
- // Returns an iterator over the SortedMap.
5496
- getIterator() {
5497
- return new SortedMapIterator(this.root, null, this.comparator, false);
5326
+ // If there is an additional bound, compare the values against the existing
5327
+ // range to see if we can narrow the scope.
5328
+ if (bound !== null) {
5329
+ for (let i = 0; i < target.orderBy.length; ++i) {
5330
+ const orderBy = target.orderBy[i];
5331
+ if (orderBy.field.isEqual(fieldPath)) {
5332
+ const cursorValue = bound.position[i];
5333
+ if (upperBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) > 0) {
5334
+ value = cursorValue;
5335
+ inclusive = bound.inclusive;
5336
+ }
5337
+ break;
5338
+ }
5339
+ }
5498
5340
  }
5499
- getIteratorFrom(key) {
5500
- return new SortedMapIterator(this.root, key, this.comparator, false);
5341
+ return { value, inclusive };
5342
+ }
5343
+ /** Returns the number of segments of a perfect index for this target. */
5344
+ function targetGetSegmentCount(target) {
5345
+ let fields = new SortedSet(FieldPath$1.comparator);
5346
+ let hasArraySegment = false;
5347
+ for (const filter of target.filters) {
5348
+ // TODO(orquery): Use the flattened filters here
5349
+ const fieldFilter = filter;
5350
+ // __name__ is not an explicit segment of any index, so we don't need to
5351
+ // count it.
5352
+ if (fieldFilter.field.isKeyField()) {
5353
+ continue;
5354
+ }
5355
+ // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
5356
+ // For instance, it is possible to have an index for "a ARRAY a ASC". Even
5357
+ // though these are on the same field, they should be counted as two
5358
+ // separate segments in an index.
5359
+ if (fieldFilter.op === "array-contains" /* ARRAY_CONTAINS */ ||
5360
+ fieldFilter.op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5361
+ hasArraySegment = true;
5362
+ }
5363
+ else {
5364
+ fields = fields.add(fieldFilter.field);
5365
+ }
5501
5366
  }
5502
- getReverseIterator() {
5503
- return new SortedMapIterator(this.root, null, this.comparator, true);
5367
+ for (const orderBy of target.orderBy) {
5368
+ // __name__ is not an explicit segment of any index, so we don't need to
5369
+ // count it.
5370
+ if (!orderBy.field.isKeyField()) {
5371
+ fields = fields.add(orderBy.field);
5372
+ }
5504
5373
  }
5505
- getReverseIteratorFrom(key) {
5506
- return new SortedMapIterator(this.root, key, this.comparator, true);
5374
+ return fields.size + (hasArraySegment ? 1 : 0);
5375
+ }
5376
+ class Filter {
5377
+ }
5378
+ class FieldFilter extends Filter {
5379
+ constructor(field, op, value) {
5380
+ super();
5381
+ this.field = field;
5382
+ this.op = op;
5383
+ this.value = value;
5507
5384
  }
5508
- } // end SortedMap
5509
- // An iterator over an LLRBNode.
5510
- class SortedMapIterator {
5511
- constructor(node, startKey, comparator, isReverse) {
5512
- this.isReverse = isReverse;
5513
- this.nodeStack = [];
5514
- let cmp = 1;
5515
- while (!node.isEmpty()) {
5516
- cmp = startKey ? comparator(node.key, startKey) : 1;
5517
- // flip the comparison if we're going in reverse
5518
- if (startKey && isReverse) {
5519
- cmp *= -1;
5520
- }
5521
- if (cmp < 0) {
5522
- // This node is less than our start key. ignore it
5523
- if (this.isReverse) {
5524
- node = node.left;
5525
- }
5526
- else {
5527
- node = node.right;
5528
- }
5529
- }
5530
- else if (cmp === 0) {
5531
- // This node is exactly equal to our start key. Push it on the stack,
5532
- // but stop iterating;
5533
- this.nodeStack.push(node);
5534
- break;
5385
+ /**
5386
+ * Creates a filter based on the provided arguments.
5387
+ */
5388
+ static create(field, op, value) {
5389
+ if (field.isKeyField()) {
5390
+ if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
5391
+ return this.createKeyFieldInFilter(field, op, value);
5535
5392
  }
5536
5393
  else {
5537
- // This node is greater than our start key, add it to the stack and move
5538
- // to the next one
5539
- this.nodeStack.push(node);
5540
- if (this.isReverse) {
5541
- node = node.right;
5542
- }
5543
- else {
5544
- node = node.left;
5545
- }
5394
+ return new KeyFieldFilter(field, op, value);
5546
5395
  }
5547
5396
  }
5548
- }
5549
- getNext() {
5550
- let node = this.nodeStack.pop();
5551
- const result = { key: node.key, value: node.value };
5552
- if (this.isReverse) {
5553
- node = node.left;
5554
- while (!node.isEmpty()) {
5555
- this.nodeStack.push(node);
5556
- node = node.right;
5557
- }
5397
+ else if (op === "array-contains" /* ARRAY_CONTAINS */) {
5398
+ return new ArrayContainsFilter(field, value);
5399
+ }
5400
+ else if (op === "in" /* IN */) {
5401
+ return new InFilter(field, value);
5402
+ }
5403
+ else if (op === "not-in" /* NOT_IN */) {
5404
+ return new NotInFilter(field, value);
5405
+ }
5406
+ else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5407
+ return new ArrayContainsAnyFilter(field, value);
5558
5408
  }
5559
5409
  else {
5560
- node = node.right;
5561
- while (!node.isEmpty()) {
5562
- this.nodeStack.push(node);
5563
- node = node.left;
5564
- }
5410
+ return new FieldFilter(field, op, value);
5411
+ }
5412
+ }
5413
+ static createKeyFieldInFilter(field, op, value) {
5414
+ return op === "in" /* IN */
5415
+ ? new KeyFieldInFilter(field, value)
5416
+ : new KeyFieldNotInFilter(field, value);
5417
+ }
5418
+ matches(doc) {
5419
+ const other = doc.data.field(this.field);
5420
+ // Types do not have to match in NOT_EQUAL filters.
5421
+ if (this.op === "!=" /* NOT_EQUAL */) {
5422
+ return (other !== null &&
5423
+ this.matchesComparison(valueCompare(other, this.value)));
5424
+ }
5425
+ // Only compare types with matching backend order (such as double and int).
5426
+ return (other !== null &&
5427
+ typeOrder(this.value) === typeOrder(other) &&
5428
+ this.matchesComparison(valueCompare(other, this.value)));
5429
+ }
5430
+ matchesComparison(comparison) {
5431
+ switch (this.op) {
5432
+ case "<" /* LESS_THAN */:
5433
+ return comparison < 0;
5434
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5435
+ return comparison <= 0;
5436
+ case "==" /* EQUAL */:
5437
+ return comparison === 0;
5438
+ case "!=" /* NOT_EQUAL */:
5439
+ return comparison !== 0;
5440
+ case ">" /* GREATER_THAN */:
5441
+ return comparison > 0;
5442
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5443
+ return comparison >= 0;
5444
+ default:
5445
+ return fail();
5565
5446
  }
5566
- return result;
5567
5447
  }
5568
- hasNext() {
5569
- return this.nodeStack.length > 0;
5448
+ isInequality() {
5449
+ return ([
5450
+ "<" /* LESS_THAN */,
5451
+ "<=" /* LESS_THAN_OR_EQUAL */,
5452
+ ">" /* GREATER_THAN */,
5453
+ ">=" /* GREATER_THAN_OR_EQUAL */,
5454
+ "!=" /* NOT_EQUAL */,
5455
+ "not-in" /* NOT_IN */
5456
+ ].indexOf(this.op) >= 0);
5570
5457
  }
5571
- peek() {
5572
- if (this.nodeStack.length === 0) {
5573
- return null;
5574
- }
5575
- const node = this.nodeStack[this.nodeStack.length - 1];
5576
- return { key: node.key, value: node.value };
5458
+ }
5459
+ function canonifyFilter(filter) {
5460
+ // TODO(b/29183165): Technically, this won't be unique if two values have
5461
+ // the same description, such as the int 3 and the string "3". So we should
5462
+ // add the types in here somehow, too.
5463
+ return (filter.field.canonicalString() +
5464
+ filter.op.toString() +
5465
+ canonicalId(filter.value));
5466
+ }
5467
+ function filterEquals(f1, f2) {
5468
+ return (f1.op === f2.op &&
5469
+ f1.field.isEqual(f2.field) &&
5470
+ valueEquals(f1.value, f2.value));
5471
+ }
5472
+ /** Returns a debug description for `filter`. */
5473
+ function stringifyFilter(filter) {
5474
+ return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
5475
+ }
5476
+ /** Filter that matches on key fields (i.e. '__name__'). */
5477
+ class KeyFieldFilter extends FieldFilter {
5478
+ constructor(field, op, value) {
5479
+ super(field, op, value);
5480
+ this.key = DocumentKey.fromName(value.referenceValue);
5577
5481
  }
5578
- } // end SortedMapIterator
5579
- // Represents a node in a Left-leaning Red-Black tree.
5580
- class LLRBNode {
5581
- constructor(key, value, color, left, right) {
5582
- this.key = key;
5583
- this.value = value;
5584
- this.color = color != null ? color : LLRBNode.RED;
5585
- this.left = left != null ? left : LLRBNode.EMPTY;
5586
- this.right = right != null ? right : LLRBNode.EMPTY;
5587
- this.size = this.left.size + 1 + this.right.size;
5482
+ matches(doc) {
5483
+ const comparison = DocumentKey.comparator(doc.key, this.key);
5484
+ return this.matchesComparison(comparison);
5588
5485
  }
5589
- // Returns a copy of the current node, optionally replacing pieces of it.
5590
- copy(key, value, color, left, right) {
5591
- 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);
5486
+ }
5487
+ /** Filter that matches on key fields within an array. */
5488
+ class KeyFieldInFilter extends FieldFilter {
5489
+ constructor(field, value) {
5490
+ super(field, "in" /* IN */, value);
5491
+ this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
5592
5492
  }
5593
- isEmpty() {
5594
- return false;
5493
+ matches(doc) {
5494
+ return this.keys.some(key => key.isEqual(doc.key));
5595
5495
  }
5596
- // Traverses the tree in key order and calls the specified action function
5597
- // for each node. If action returns true, traversal is aborted.
5598
- // Returns the first truthy value returned by action, or the last falsey
5599
- // value returned by action.
5600
- inorderTraversal(action) {
5601
- return (this.left.inorderTraversal(action) ||
5602
- action(this.key, this.value) ||
5603
- this.right.inorderTraversal(action));
5496
+ }
5497
+ /** Filter that matches on key fields not present within an array. */
5498
+ class KeyFieldNotInFilter extends FieldFilter {
5499
+ constructor(field, value) {
5500
+ super(field, "not-in" /* NOT_IN */, value);
5501
+ this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
5604
5502
  }
5605
- // Traverses the tree in reverse key order and calls the specified action
5606
- // function for each node. If action returns true, traversal is aborted.
5607
- // Returns the first truthy value returned by action, or the last falsey
5608
- // value returned by action.
5609
- reverseTraversal(action) {
5610
- return (this.right.reverseTraversal(action) ||
5611
- action(this.key, this.value) ||
5612
- this.left.reverseTraversal(action));
5503
+ matches(doc) {
5504
+ return !this.keys.some(key => key.isEqual(doc.key));
5613
5505
  }
5614
- // Returns the minimum node in the tree.
5615
- min() {
5616
- if (this.left.isEmpty()) {
5617
- return this;
5618
- }
5619
- else {
5620
- return this.left.min();
5621
- }
5506
+ }
5507
+ function extractDocumentKeysFromArrayValue(op, value) {
5508
+ var _a;
5509
+ return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
5510
+ return DocumentKey.fromName(v.referenceValue);
5511
+ });
5512
+ }
5513
+ /** A Filter that implements the array-contains operator. */
5514
+ class ArrayContainsFilter extends FieldFilter {
5515
+ constructor(field, value) {
5516
+ super(field, "array-contains" /* ARRAY_CONTAINS */, value);
5622
5517
  }
5623
- // Returns the maximum key in the tree.
5624
- minKey() {
5625
- return this.min().key;
5518
+ matches(doc) {
5519
+ const other = doc.data.field(this.field);
5520
+ return isArray(other) && arrayValueContains(other.arrayValue, this.value);
5626
5521
  }
5627
- // Returns the maximum key in the tree.
5628
- maxKey() {
5629
- if (this.right.isEmpty()) {
5630
- return this.key;
5631
- }
5632
- else {
5633
- return this.right.maxKey();
5634
- }
5522
+ }
5523
+ /** A Filter that implements the IN operator. */
5524
+ class InFilter extends FieldFilter {
5525
+ constructor(field, value) {
5526
+ super(field, "in" /* IN */, value);
5635
5527
  }
5636
- // Returns new tree, with the key/value added.
5637
- insert(key, value, comparator) {
5638
- let n = this;
5639
- const cmp = comparator(key, n.key);
5640
- if (cmp < 0) {
5641
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
5642
- }
5643
- else if (cmp === 0) {
5644
- n = n.copy(null, value, null, null, null);
5645
- }
5646
- else {
5647
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
5648
- }
5649
- return n.fixUp();
5528
+ matches(doc) {
5529
+ const other = doc.data.field(this.field);
5530
+ return other !== null && arrayValueContains(this.value.arrayValue, other);
5650
5531
  }
5651
- removeMin() {
5652
- if (this.left.isEmpty()) {
5653
- return LLRBNode.EMPTY;
5654
- }
5655
- let n = this;
5656
- if (!n.left.isRed() && !n.left.left.isRed()) {
5657
- n = n.moveRedLeft();
5658
- }
5659
- n = n.copy(null, null, null, n.left.removeMin(), null);
5660
- return n.fixUp();
5532
+ }
5533
+ /** A Filter that implements the not-in operator. */
5534
+ class NotInFilter extends FieldFilter {
5535
+ constructor(field, value) {
5536
+ super(field, "not-in" /* NOT_IN */, value);
5661
5537
  }
5662
- // Returns new tree, with the specified item removed.
5663
- remove(key, comparator) {
5664
- let smallest;
5665
- let n = this;
5666
- if (comparator(key, n.key) < 0) {
5667
- if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
5668
- n = n.moveRedLeft();
5669
- }
5670
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
5538
+ matches(doc) {
5539
+ if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
5540
+ return false;
5671
5541
  }
5672
- else {
5673
- if (n.left.isRed()) {
5674
- n = n.rotateRight();
5675
- }
5676
- if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
5677
- n = n.moveRedRight();
5678
- }
5679
- if (comparator(key, n.key) === 0) {
5680
- if (n.right.isEmpty()) {
5681
- return LLRBNode.EMPTY;
5682
- }
5683
- else {
5684
- smallest = n.right.min();
5685
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
5686
- }
5687
- }
5688
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
5542
+ const other = doc.data.field(this.field);
5543
+ return other !== null && !arrayValueContains(this.value.arrayValue, other);
5544
+ }
5545
+ }
5546
+ /** A Filter that implements the array-contains-any operator. */
5547
+ class ArrayContainsAnyFilter extends FieldFilter {
5548
+ constructor(field, value) {
5549
+ super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
5550
+ }
5551
+ matches(doc) {
5552
+ const other = doc.data.field(this.field);
5553
+ if (!isArray(other) || !other.arrayValue.values) {
5554
+ return false;
5689
5555
  }
5690
- return n.fixUp();
5556
+ return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
5691
5557
  }
5692
- isRed() {
5693
- return this.color;
5558
+ }
5559
+ /**
5560
+ * Represents a bound of a query.
5561
+ *
5562
+ * The bound is specified with the given components representing a position and
5563
+ * whether it's just before or just after the position (relative to whatever the
5564
+ * query order is).
5565
+ *
5566
+ * The position represents a logical index position for a query. It's a prefix
5567
+ * of values for the (potentially implicit) order by clauses of a query.
5568
+ *
5569
+ * Bound provides a function to determine whether a document comes before or
5570
+ * after a bound. This is influenced by whether the position is just before or
5571
+ * just after the provided values.
5572
+ */
5573
+ class Bound {
5574
+ constructor(position, inclusive) {
5575
+ this.position = position;
5576
+ this.inclusive = inclusive;
5694
5577
  }
5695
- // Returns new tree after performing any needed rotations.
5696
- fixUp() {
5697
- let n = this;
5698
- if (n.right.isRed() && !n.left.isRed()) {
5699
- n = n.rotateLeft();
5578
+ }
5579
+ /**
5580
+ * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
5581
+ */
5582
+ class OrderBy {
5583
+ constructor(field, dir = "asc" /* ASCENDING */) {
5584
+ this.field = field;
5585
+ this.dir = dir;
5586
+ }
5587
+ }
5588
+ function canonifyOrderBy(orderBy) {
5589
+ // TODO(b/29183165): Make this collision robust.
5590
+ return orderBy.field.canonicalString() + orderBy.dir;
5591
+ }
5592
+ function stringifyOrderBy(orderBy) {
5593
+ return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
5594
+ }
5595
+ function orderByEquals(left, right) {
5596
+ return left.dir === right.dir && left.field.isEqual(right.field);
5597
+ }
5598
+ function boundCompareToDocument(bound, orderBy, doc) {
5599
+ let comparison = 0;
5600
+ for (let i = 0; i < bound.position.length; i++) {
5601
+ const orderByComponent = orderBy[i];
5602
+ const component = bound.position[i];
5603
+ if (orderByComponent.field.isKeyField()) {
5604
+ comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
5700
5605
  }
5701
- if (n.left.isRed() && n.left.left.isRed()) {
5702
- n = n.rotateRight();
5606
+ else {
5607
+ const docValue = doc.data.field(orderByComponent.field);
5608
+ comparison = valueCompare(component, docValue);
5703
5609
  }
5704
- if (n.left.isRed() && n.right.isRed()) {
5705
- n = n.colorFlip();
5610
+ if (orderByComponent.dir === "desc" /* DESCENDING */) {
5611
+ comparison = comparison * -1;
5706
5612
  }
5707
- return n;
5708
- }
5709
- moveRedLeft() {
5710
- let n = this.colorFlip();
5711
- if (n.right.left.isRed()) {
5712
- n = n.copy(null, null, null, null, n.right.rotateRight());
5713
- n = n.rotateLeft();
5714
- n = n.colorFlip();
5613
+ if (comparison !== 0) {
5614
+ break;
5715
5615
  }
5716
- return n;
5717
5616
  }
5718
- moveRedRight() {
5719
- let n = this.colorFlip();
5720
- if (n.left.left.isRed()) {
5721
- n = n.rotateRight();
5722
- n = n.colorFlip();
5723
- }
5724
- return n;
5617
+ return comparison;
5618
+ }
5619
+ /**
5620
+ * Returns true if a document sorts after a bound using the provided sort
5621
+ * order.
5622
+ */
5623
+ function boundSortsAfterDocument(bound, orderBy, doc) {
5624
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5625
+ return bound.inclusive ? comparison >= 0 : comparison > 0;
5626
+ }
5627
+ /**
5628
+ * Returns true if a document sorts before a bound using the provided sort
5629
+ * order.
5630
+ */
5631
+ function boundSortsBeforeDocument(bound, orderBy, doc) {
5632
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5633
+ return bound.inclusive ? comparison <= 0 : comparison < 0;
5634
+ }
5635
+ function boundEquals(left, right) {
5636
+ if (left === null) {
5637
+ return right === null;
5725
5638
  }
5726
- rotateLeft() {
5727
- const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
5728
- return this.right.copy(null, null, this.color, nl, null);
5639
+ else if (right === null) {
5640
+ return false;
5729
5641
  }
5730
- rotateRight() {
5731
- const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
5732
- return this.left.copy(null, null, this.color, null, nr);
5642
+ if (left.inclusive !== right.inclusive ||
5643
+ left.position.length !== right.position.length) {
5644
+ return false;
5733
5645
  }
5734
- colorFlip() {
5735
- const left = this.left.copy(null, null, !this.left.color, null, null);
5736
- const right = this.right.copy(null, null, !this.right.color, null, null);
5737
- return this.copy(null, null, !this.color, left, right);
5646
+ for (let i = 0; i < left.position.length; i++) {
5647
+ const leftPosition = left.position[i];
5648
+ const rightPosition = right.position[i];
5649
+ if (!valueEquals(leftPosition, rightPosition)) {
5650
+ return false;
5651
+ }
5738
5652
  }
5739
- // For testing.
5740
- checkMaxDepth() {
5741
- const blackDepth = this.check();
5742
- if (Math.pow(2.0, blackDepth) <= this.size + 1) {
5743
- return true;
5653
+ return true;
5654
+ }
5655
+
5656
+ /**
5657
+ * @license
5658
+ * Copyright 2017 Google LLC
5659
+ *
5660
+ * Licensed under the Apache License, Version 2.0 (the "License");
5661
+ * you may not use this file except in compliance with the License.
5662
+ * You may obtain a copy of the License at
5663
+ *
5664
+ * http://www.apache.org/licenses/LICENSE-2.0
5665
+ *
5666
+ * Unless required by applicable law or agreed to in writing, software
5667
+ * distributed under the License is distributed on an "AS IS" BASIS,
5668
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5669
+ * See the License for the specific language governing permissions and
5670
+ * limitations under the License.
5671
+ */
5672
+ /**
5673
+ * Query encapsulates all the query attributes we support in the SDK. It can
5674
+ * be run against the LocalStore, as well as be converted to a `Target` to
5675
+ * query the RemoteStore results.
5676
+ *
5677
+ * Visible for testing.
5678
+ */
5679
+ class QueryImpl {
5680
+ /**
5681
+ * Initializes a Query with a path and optional additional query constraints.
5682
+ * Path must currently be empty if this is a collection group query.
5683
+ */
5684
+ constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
5685
+ this.path = path;
5686
+ this.collectionGroup = collectionGroup;
5687
+ this.explicitOrderBy = explicitOrderBy;
5688
+ this.filters = filters;
5689
+ this.limit = limit;
5690
+ this.limitType = limitType;
5691
+ this.startAt = startAt;
5692
+ this.endAt = endAt;
5693
+ this.memoizedOrderBy = null;
5694
+ // The corresponding `Target` of this `Query` instance.
5695
+ this.memoizedTarget = null;
5696
+ if (this.startAt) ;
5697
+ if (this.endAt) ;
5698
+ }
5699
+ }
5700
+ /** Creates a new Query instance with the options provided. */
5701
+ function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
5702
+ return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
5703
+ }
5704
+ /** Creates a new Query for a query that matches all documents at `path` */
5705
+ function newQueryForPath(path) {
5706
+ return new QueryImpl(path);
5707
+ }
5708
+ /**
5709
+ * Helper to convert a collection group query into a collection query at a
5710
+ * specific path. This is used when executing collection group queries, since
5711
+ * we have to split the query into a set of collection queries at multiple
5712
+ * paths.
5713
+ */
5714
+ function asCollectionQueryAtPath(query, path) {
5715
+ return new QueryImpl(path,
5716
+ /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5717
+ }
5718
+ /**
5719
+ * Returns true if this query does not specify any query constraints that
5720
+ * could remove results.
5721
+ */
5722
+ function queryMatchesAllDocuments(query) {
5723
+ return (query.filters.length === 0 &&
5724
+ query.limit === null &&
5725
+ query.startAt == null &&
5726
+ query.endAt == null &&
5727
+ (query.explicitOrderBy.length === 0 ||
5728
+ (query.explicitOrderBy.length === 1 &&
5729
+ query.explicitOrderBy[0].field.isKeyField())));
5730
+ }
5731
+ function getFirstOrderByField(query) {
5732
+ return query.explicitOrderBy.length > 0
5733
+ ? query.explicitOrderBy[0].field
5734
+ : null;
5735
+ }
5736
+ function getInequalityFilterField(query) {
5737
+ for (const filter of query.filters) {
5738
+ if (filter.isInequality()) {
5739
+ return filter.field;
5744
5740
  }
5745
- else {
5746
- return false;
5741
+ }
5742
+ return null;
5743
+ }
5744
+ /**
5745
+ * Checks if any of the provided Operators are included in the query and
5746
+ * returns the first one that is, or null if none are.
5747
+ */
5748
+ function findFilterOperator(query, operators) {
5749
+ for (const filter of query.filters) {
5750
+ if (operators.indexOf(filter.op) >= 0) {
5751
+ return filter.op;
5747
5752
  }
5748
5753
  }
5749
- // In a balanced RB tree, the black-depth (number of black nodes) from root to
5750
- // leaves is equal on both sides. This function verifies that or asserts.
5751
- check() {
5752
- if (this.isRed() && this.left.isRed()) {
5753
- throw fail();
5754
+ return null;
5755
+ }
5756
+ /**
5757
+ * Creates a new Query for a collection group query that matches all documents
5758
+ * within the provided collection group.
5759
+ */
5760
+ function newQueryForCollectionGroup(collectionId) {
5761
+ return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5762
+ }
5763
+ /**
5764
+ * Returns whether the query matches a single document by path (rather than a
5765
+ * collection).
5766
+ */
5767
+ function isDocumentQuery$1(query) {
5768
+ return (DocumentKey.isDocumentKey(query.path) &&
5769
+ query.collectionGroup === null &&
5770
+ query.filters.length === 0);
5771
+ }
5772
+ /**
5773
+ * Returns whether the query matches a collection group rather than a specific
5774
+ * collection.
5775
+ */
5776
+ function isCollectionGroupQuery(query) {
5777
+ return query.collectionGroup !== null;
5778
+ }
5779
+ /**
5780
+ * Returns the implicit order by constraint that is used to execute the Query,
5781
+ * which can be different from the order by constraints the user provided (e.g.
5782
+ * the SDK and backend always orders by `__name__`).
5783
+ */
5784
+ function queryOrderBy(query) {
5785
+ const queryImpl = debugCast(query);
5786
+ if (queryImpl.memoizedOrderBy === null) {
5787
+ queryImpl.memoizedOrderBy = [];
5788
+ const inequalityField = getInequalityFilterField(queryImpl);
5789
+ const firstOrderByField = getFirstOrderByField(queryImpl);
5790
+ if (inequalityField !== null && firstOrderByField === null) {
5791
+ // In order to implicitly add key ordering, we must also add the
5792
+ // inequality filter field for it to be a valid query.
5793
+ // Note that the default inequality field and key ordering is ascending.
5794
+ if (!inequalityField.isKeyField()) {
5795
+ queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5796
+ }
5797
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
5754
5798
  }
5755
- if (this.right.isRed()) {
5756
- throw fail();
5799
+ else {
5800
+ let foundKeyOrdering = false;
5801
+ for (const orderBy of queryImpl.explicitOrderBy) {
5802
+ queryImpl.memoizedOrderBy.push(orderBy);
5803
+ if (orderBy.field.isKeyField()) {
5804
+ foundKeyOrdering = true;
5805
+ }
5806
+ }
5807
+ if (!foundKeyOrdering) {
5808
+ // The order of the implicit key ordering always matches the last
5809
+ // explicit order by
5810
+ const lastDirection = queryImpl.explicitOrderBy.length > 0
5811
+ ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5812
+ .dir
5813
+ : "asc" /* ASCENDING */;
5814
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
5815
+ }
5757
5816
  }
5758
- const blackDepth = this.left.check();
5759
- if (blackDepth !== this.right.check()) {
5760
- throw fail();
5817
+ }
5818
+ return queryImpl.memoizedOrderBy;
5819
+ }
5820
+ /**
5821
+ * Converts this `Query` instance to it's corresponding `Target` representation.
5822
+ */
5823
+ function queryToTarget(query) {
5824
+ const queryImpl = debugCast(query);
5825
+ if (!queryImpl.memoizedTarget) {
5826
+ if (queryImpl.limitType === "F" /* First */) {
5827
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
5761
5828
  }
5762
5829
  else {
5763
- return blackDepth + (this.isRed() ? 0 : 1);
5830
+ // Flip the orderBy directions since we want the last results
5831
+ const orderBys = [];
5832
+ for (const orderBy of queryOrderBy(queryImpl)) {
5833
+ const dir = orderBy.dir === "desc" /* DESCENDING */
5834
+ ? "asc" /* ASCENDING */
5835
+ : "desc" /* DESCENDING */;
5836
+ orderBys.push(new OrderBy(orderBy.field, dir));
5837
+ }
5838
+ // We need to swap the cursors to match the now-flipped query ordering.
5839
+ const startAt = queryImpl.endAt
5840
+ ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)
5841
+ : null;
5842
+ const endAt = queryImpl.startAt
5843
+ ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)
5844
+ : null;
5845
+ // Now return as a LimitType.First query.
5846
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5764
5847
  }
5765
5848
  }
5766
- } // end LLRBNode
5767
- // Empty node is shared between all LLRB trees.
5768
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5769
- LLRBNode.EMPTY = null;
5770
- LLRBNode.RED = true;
5771
- LLRBNode.BLACK = false;
5772
- // Represents an empty node (a leaf node in the Red-Black Tree).
5773
- class LLRBEmptyNode {
5774
- constructor() {
5775
- this.size = 0;
5776
- }
5777
- get key() {
5778
- throw fail();
5779
- }
5780
- get value() {
5781
- throw fail();
5782
- }
5783
- get color() {
5784
- throw fail();
5785
- }
5786
- get left() {
5787
- throw fail();
5788
- }
5789
- get right() {
5790
- throw fail();
5791
- }
5792
- // Returns a copy of the current node.
5793
- copy(key, value, color, left, right) {
5794
- return this;
5849
+ return queryImpl.memoizedTarget;
5850
+ }
5851
+ function queryWithAddedFilter(query, filter) {
5852
+ const newFilters = query.filters.concat([filter]);
5853
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5854
+ }
5855
+ function queryWithAddedOrderBy(query, orderBy) {
5856
+ // TODO(dimond): validate that orderBy does not list the same key twice.
5857
+ const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5858
+ return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5859
+ }
5860
+ function queryWithLimit(query, limit, limitType) {
5861
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5862
+ }
5863
+ function queryWithStartAt(query, bound) {
5864
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5865
+ }
5866
+ function queryWithEndAt(query, bound) {
5867
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5868
+ }
5869
+ function queryEquals(left, right) {
5870
+ return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5871
+ left.limitType === right.limitType);
5872
+ }
5873
+ // TODO(b/29183165): This is used to get a unique string from a query to, for
5874
+ // example, use as a dictionary key, but the implementation is subject to
5875
+ // collisions. Make it collision-free.
5876
+ function canonifyQuery(query) {
5877
+ return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5878
+ }
5879
+ function stringifyQuery(query) {
5880
+ return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5881
+ }
5882
+ /** Returns whether `doc` matches the constraints of `query`. */
5883
+ function queryMatches(query, doc) {
5884
+ return (doc.isFoundDocument() &&
5885
+ queryMatchesPathAndCollectionGroup(query, doc) &&
5886
+ queryMatchesOrderBy(query, doc) &&
5887
+ queryMatchesFilters(query, doc) &&
5888
+ queryMatchesBounds(query, doc));
5889
+ }
5890
+ function queryMatchesPathAndCollectionGroup(query, doc) {
5891
+ const docPath = doc.key.path;
5892
+ if (query.collectionGroup !== null) {
5893
+ // NOTE: this.path is currently always empty since we don't expose Collection
5894
+ // Group queries rooted at a document path yet.
5895
+ return (doc.key.hasCollectionId(query.collectionGroup) &&
5896
+ query.path.isPrefixOf(docPath));
5795
5897
  }
5796
- // Returns a copy of the tree, with the specified key/value added.
5797
- insert(key, value, comparator) {
5798
- return new LLRBNode(key, value);
5898
+ else if (DocumentKey.isDocumentKey(query.path)) {
5899
+ // exact match for document queries
5900
+ return query.path.isEqual(docPath);
5799
5901
  }
5800
- // Returns a copy of the tree, with the specified key removed.
5801
- remove(key, comparator) {
5802
- return this;
5902
+ else {
5903
+ // shallow ancestor queries by default
5904
+ return query.path.isImmediateParentOf(docPath);
5803
5905
  }
5804
- isEmpty() {
5805
- return true;
5906
+ }
5907
+ /**
5908
+ * A document must have a value for every ordering clause in order to show up
5909
+ * in the results.
5910
+ */
5911
+ function queryMatchesOrderBy(query, doc) {
5912
+ for (const orderBy of query.explicitOrderBy) {
5913
+ // order by key always matches
5914
+ if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5915
+ return false;
5916
+ }
5806
5917
  }
5807
- inorderTraversal(action) {
5808
- return false;
5918
+ return true;
5919
+ }
5920
+ function queryMatchesFilters(query, doc) {
5921
+ for (const filter of query.filters) {
5922
+ if (!filter.matches(doc)) {
5923
+ return false;
5924
+ }
5809
5925
  }
5810
- reverseTraversal(action) {
5926
+ return true;
5927
+ }
5928
+ /** Makes sure a document is within the bounds, if provided. */
5929
+ function queryMatchesBounds(query, doc) {
5930
+ if (query.startAt &&
5931
+ !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5811
5932
  return false;
5812
5933
  }
5813
- minKey() {
5814
- return null;
5815
- }
5816
- maxKey() {
5817
- return null;
5818
- }
5819
- isRed() {
5934
+ if (query.endAt &&
5935
+ !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5820
5936
  return false;
5821
5937
  }
5822
- // For testing.
5823
- checkMaxDepth() {
5824
- return true;
5825
- }
5826
- check() {
5938
+ return true;
5939
+ }
5940
+ /**
5941
+ * Returns the collection group that this query targets.
5942
+ *
5943
+ * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5944
+ * synchronization for query results.
5945
+ */
5946
+ function queryCollectionGroup(query) {
5947
+ return (query.collectionGroup ||
5948
+ (query.path.length % 2 === 1
5949
+ ? query.path.lastSegment()
5950
+ : query.path.get(query.path.length - 2)));
5951
+ }
5952
+ /**
5953
+ * Returns a new comparator function that can be used to compare two documents
5954
+ * based on the Query's ordering constraint.
5955
+ */
5956
+ function newQueryComparator(query) {
5957
+ return (d1, d2) => {
5958
+ let comparedOnKeyField = false;
5959
+ for (const orderBy of queryOrderBy(query)) {
5960
+ const comp = compareDocs(orderBy, d1, d2);
5961
+ if (comp !== 0) {
5962
+ return comp;
5963
+ }
5964
+ comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
5965
+ }
5827
5966
  return 0;
5967
+ };
5968
+ }
5969
+ function compareDocs(orderBy, d1, d2) {
5970
+ const comparison = orderBy.field.isKeyField()
5971
+ ? DocumentKey.comparator(d1.key, d2.key)
5972
+ : compareDocumentsByField(orderBy.field, d1, d2);
5973
+ switch (orderBy.dir) {
5974
+ case "asc" /* ASCENDING */:
5975
+ return comparison;
5976
+ case "desc" /* DESCENDING */:
5977
+ return -1 * comparison;
5978
+ default:
5979
+ return fail();
5828
5980
  }
5829
- } // end LLRBEmptyNode
5830
- LLRBNode.EMPTY = new LLRBEmptyNode();
5981
+ }
5831
5982
 
5832
5983
  /**
5833
5984
  * @license
@@ -5846,218 +5997,97 @@ LLRBNode.EMPTY = new LLRBEmptyNode();
5846
5997
  * limitations under the License.
5847
5998
  */
5848
5999
  /**
5849
- * SortedSet is an immutable (copy-on-write) collection that holds elements
5850
- * in order specified by the provided comparator.
5851
- *
5852
- * NOTE: if provided comparator returns 0 for two elements, we consider them to
5853
- * be equal!
6000
+ * A map implementation that uses objects as keys. Objects must have an
6001
+ * associated equals function and must be immutable. Entries in the map are
6002
+ * stored together with the key being produced from the mapKeyFn. This map
6003
+ * automatically handles collisions of keys.
5854
6004
  */
5855
- class SortedSet {
5856
- constructor(comparator) {
5857
- this.comparator = comparator;
5858
- this.data = new SortedMap(this.comparator);
5859
- }
5860
- has(elem) {
5861
- return this.data.get(elem) !== null;
5862
- }
5863
- first() {
5864
- return this.data.minKey();
5865
- }
5866
- last() {
5867
- return this.data.maxKey();
5868
- }
5869
- get size() {
5870
- return this.data.size;
5871
- }
5872
- indexOf(elem) {
5873
- return this.data.indexOf(elem);
5874
- }
5875
- /** Iterates elements in order defined by "comparator" */
5876
- forEach(cb) {
5877
- this.data.inorderTraversal((k, v) => {
5878
- cb(k);
5879
- return false;
5880
- });
5881
- }
5882
- /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
5883
- forEachInRange(range, cb) {
5884
- const iter = this.data.getIteratorFrom(range[0]);
5885
- while (iter.hasNext()) {
5886
- const elem = iter.getNext();
5887
- if (this.comparator(elem.key, range[1]) >= 0) {
5888
- return;
5889
- }
5890
- cb(elem.key);
5891
- }
6005
+ class ObjectMap {
6006
+ constructor(mapKeyFn, equalsFn) {
6007
+ this.mapKeyFn = mapKeyFn;
6008
+ this.equalsFn = equalsFn;
6009
+ /**
6010
+ * The inner map for a key/value pair. Due to the possibility of collisions we
6011
+ * keep a list of entries that we do a linear search through to find an actual
6012
+ * match. Note that collisions should be rare, so we still expect near
6013
+ * constant time lookups in practice.
6014
+ */
6015
+ this.inner = {};
6016
+ /** The number of entries stored in the map */
6017
+ this.innerSize = 0;
5892
6018
  }
5893
- /**
5894
- * Iterates over `elem`s such that: start &lt;= elem until false is returned.
5895
- */
5896
- forEachWhile(cb, start) {
5897
- let iter;
5898
- if (start !== undefined) {
5899
- iter = this.data.getIteratorFrom(start);
5900
- }
5901
- else {
5902
- iter = this.data.getIterator();
6019
+ /** Get a value for this key, or undefined if it does not exist. */
6020
+ get(key) {
6021
+ const id = this.mapKeyFn(key);
6022
+ const matches = this.inner[id];
6023
+ if (matches === undefined) {
6024
+ return undefined;
5903
6025
  }
5904
- while (iter.hasNext()) {
5905
- const elem = iter.getNext();
5906
- const result = cb(elem.key);
5907
- if (!result) {
5908
- return;
6026
+ for (const [otherKey, value] of matches) {
6027
+ if (this.equalsFn(otherKey, key)) {
6028
+ return value;
5909
6029
  }
5910
6030
  }
6031
+ return undefined;
5911
6032
  }
5912
- /** Finds the least element greater than or equal to `elem`. */
5913
- firstAfterOrEqual(elem) {
5914
- const iter = this.data.getIteratorFrom(elem);
5915
- return iter.hasNext() ? iter.getNext().key : null;
5916
- }
5917
- getIterator() {
5918
- return new SortedSetIterator(this.data.getIterator());
5919
- }
5920
- getIteratorFrom(key) {
5921
- return new SortedSetIterator(this.data.getIteratorFrom(key));
5922
- }
5923
- /** Inserts or updates an element */
5924
- add(elem) {
5925
- return this.copy(this.data.remove(elem).insert(elem, true));
6033
+ has(key) {
6034
+ return this.get(key) !== undefined;
5926
6035
  }
5927
- /** Deletes an element */
5928
- delete(elem) {
5929
- if (!this.has(elem)) {
5930
- return this;
6036
+ /** Put this key and value in the map. */
6037
+ set(key, value) {
6038
+ const id = this.mapKeyFn(key);
6039
+ const matches = this.inner[id];
6040
+ if (matches === undefined) {
6041
+ this.inner[id] = [[key, value]];
6042
+ this.innerSize++;
6043
+ return;
5931
6044
  }
5932
- return this.copy(this.data.remove(elem));
5933
- }
5934
- isEmpty() {
5935
- return this.data.isEmpty();
5936
- }
5937
- unionWith(other) {
5938
- let result = this;
5939
- // Make sure `result` always refers to the larger one of the two sets.
5940
- if (result.size < other.size) {
5941
- result = other;
5942
- other = this;
6045
+ for (let i = 0; i < matches.length; i++) {
6046
+ if (this.equalsFn(matches[i][0], key)) {
6047
+ // This is updating an existing entry and does not increase `innerSize`.
6048
+ matches[i] = [key, value];
6049
+ return;
6050
+ }
5943
6051
  }
5944
- other.forEach(elem => {
5945
- result = result.add(elem);
5946
- });
5947
- return result;
6052
+ matches.push([key, value]);
6053
+ this.innerSize++;
5948
6054
  }
5949
- isEqual(other) {
5950
- if (!(other instanceof SortedSet)) {
5951
- return false;
5952
- }
5953
- if (this.size !== other.size) {
6055
+ /**
6056
+ * Remove this key from the map. Returns a boolean if anything was deleted.
6057
+ */
6058
+ delete(key) {
6059
+ const id = this.mapKeyFn(key);
6060
+ const matches = this.inner[id];
6061
+ if (matches === undefined) {
5954
6062
  return false;
5955
6063
  }
5956
- const thisIt = this.data.getIterator();
5957
- const otherIt = other.data.getIterator();
5958
- while (thisIt.hasNext()) {
5959
- const thisElem = thisIt.getNext().key;
5960
- const otherElem = otherIt.getNext().key;
5961
- if (this.comparator(thisElem, otherElem) !== 0) {
5962
- return false;
6064
+ for (let i = 0; i < matches.length; i++) {
6065
+ if (this.equalsFn(matches[i][0], key)) {
6066
+ if (matches.length === 1) {
6067
+ delete this.inner[id];
6068
+ }
6069
+ else {
6070
+ matches.splice(i, 1);
6071
+ }
6072
+ this.innerSize--;
6073
+ return true;
5963
6074
  }
5964
6075
  }
5965
- return true;
6076
+ return false;
5966
6077
  }
5967
- toArray() {
5968
- const res = [];
5969
- this.forEach(targetId => {
5970
- res.push(targetId);
6078
+ forEach(fn) {
6079
+ forEach(this.inner, (_, entries) => {
6080
+ for (const [k, v] of entries) {
6081
+ fn(k, v);
6082
+ }
5971
6083
  });
5972
- return res;
5973
- }
5974
- toString() {
5975
- const result = [];
5976
- this.forEach(elem => result.push(elem));
5977
- return 'SortedSet(' + result.toString() + ')';
5978
- }
5979
- copy(data) {
5980
- const result = new SortedSet(this.comparator);
5981
- result.data = data;
5982
- return result;
5983
- }
5984
- }
5985
- class SortedSetIterator {
5986
- constructor(iter) {
5987
- this.iter = iter;
5988
- }
5989
- getNext() {
5990
- return this.iter.getNext().key;
5991
6084
  }
5992
- hasNext() {
5993
- return this.iter.hasNext();
6085
+ isEmpty() {
6086
+ return isEmpty(this.inner);
5994
6087
  }
5995
- }
5996
- /**
5997
- * Compares two sorted sets for equality using their natural ordering. The
5998
- * method computes the intersection and invokes `onAdd` for every element that
5999
- * is in `after` but not `before`. `onRemove` is invoked for every element in
6000
- * `before` but missing from `after`.
6001
- *
6002
- * The method creates a copy of both `before` and `after` and runs in O(n log
6003
- * n), where n is the size of the two lists.
6004
- *
6005
- * @param before - The elements that exist in the original set.
6006
- * @param after - The elements to diff against the original set.
6007
- * @param comparator - The comparator for the elements in before and after.
6008
- * @param onAdd - A function to invoke for every element that is part of `
6009
- * after` but not `before`.
6010
- * @param onRemove - A function to invoke for every element that is part of
6011
- * `before` but not `after`.
6012
- */
6013
- function diffSortedSets(before, after, comparator, onAdd, onRemove) {
6014
- const beforeIt = before.getIterator();
6015
- const afterIt = after.getIterator();
6016
- let beforeValue = advanceIterator(beforeIt);
6017
- let afterValue = advanceIterator(afterIt);
6018
- // Walk through the two sets at the same time, using the ordering defined by
6019
- // `comparator`.
6020
- while (beforeValue || afterValue) {
6021
- let added = false;
6022
- let removed = false;
6023
- if (beforeValue && afterValue) {
6024
- const cmp = comparator(beforeValue, afterValue);
6025
- if (cmp < 0) {
6026
- // The element was removed if the next element in our ordered
6027
- // walkthrough is only in `before`.
6028
- removed = true;
6029
- }
6030
- else if (cmp > 0) {
6031
- // The element was added if the next element in our ordered walkthrough
6032
- // is only in `after`.
6033
- added = true;
6034
- }
6035
- }
6036
- else if (beforeValue != null) {
6037
- removed = true;
6038
- }
6039
- else {
6040
- added = true;
6041
- }
6042
- if (added) {
6043
- onAdd(afterValue);
6044
- afterValue = advanceIterator(afterIt);
6045
- }
6046
- else if (removed) {
6047
- onRemove(beforeValue);
6048
- beforeValue = advanceIterator(beforeIt);
6049
- }
6050
- else {
6051
- beforeValue = advanceIterator(beforeIt);
6052
- afterValue = advanceIterator(afterIt);
6053
- }
6088
+ size() {
6089
+ return this.innerSize;
6054
6090
  }
6055
- }
6056
- /**
6057
- * Returns the next element from the iterator or `undefined` if none available.
6058
- */
6059
- function advanceIterator(it) {
6060
- return it.hasNext() ? it.getNext() : undefined;
6061
6091
  }
6062
6092
 
6063
6093
  /**
@@ -6081,8 +6111,12 @@ function mutableDocumentMap() {
6081
6111
  return EMPTY_MUTABLE_DOCUMENT_MAP;
6082
6112
  }
6083
6113
  const EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);
6084
- function documentMap() {
6085
- return EMPTY_DOCUMENT_MAP;
6114
+ function documentMap(...docs) {
6115
+ let map = EMPTY_DOCUMENT_MAP;
6116
+ for (const doc of docs) {
6117
+ map = map.insert(doc.key, doc);
6118
+ }
6119
+ return map;
6086
6120
  }
6087
6121
  function newOverlayMap() {
6088
6122
  return new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r));
@@ -9975,9 +10009,9 @@ class MemoryIndexManager {
9975
10009
  // Field indices are not supported with memory persistence.
9976
10010
  return PersistencePromise.resolve(null);
9977
10011
  }
9978
- getFieldIndex(transaction, target) {
10012
+ getIndexType(transaction, target) {
9979
10013
  // Field indices are not supported with memory persistence.
9980
- return PersistencePromise.resolve(null);
10014
+ return PersistencePromise.resolve(0 /* NONE */);
9981
10015
  }
9982
10016
  getFieldIndexes(transaction, collectionGroup) {
9983
10017
  // Field indices are not supported with memory persistence.
@@ -9987,6 +10021,9 @@ class MemoryIndexManager {
9987
10021
  // Field indices are not supported with memory persistence.
9988
10022
  return PersistencePromise.resolve(null);
9989
10023
  }
10024
+ getMinOffset(transaction, target) {
10025
+ return PersistencePromise.resolve(IndexOffset.min());
10026
+ }
9990
10027
  updateCollectionGroup(transaction, collectionGroup, offset) {
9991
10028
  // Field indices are not supported with memory persistence.
9992
10029
  return PersistencePromise.resolve();
@@ -10162,7 +10199,7 @@ class IndexedDbIndexManager {
10162
10199
  const lowerBoundEncoded = this.encodeBound(index, subTarget, lowerBound);
10163
10200
  const upperBoundEncoded = this.encodeBound(index, subTarget, upperBound);
10164
10201
  const notInEncoded = this.encodeValues(index, subTarget, notInValues);
10165
- const indexRanges = this.generateIndexRanges(index.indexId, arrayValues, lowerBoundEncoded, !!lowerBound && lowerBound.inclusive, upperBoundEncoded, !!upperBound && upperBound.inclusive, notInEncoded);
10202
+ const indexRanges = this.generateIndexRanges(index.indexId, arrayValues, lowerBoundEncoded, lowerBound.inclusive, upperBoundEncoded, upperBound.inclusive, notInEncoded);
10166
10203
  return PersistencePromise.forEach(indexRanges, (indexRange) => {
10167
10204
  return indexEntries
10168
10205
  .loadFirst(indexRange, target.limit)
@@ -10200,22 +10237,18 @@ class IndexedDbIndexManager {
10200
10237
  // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
10201
10238
  // combined with the values from the query bounds.
10202
10239
  const totalScans = (arrayValues != null ? arrayValues.length : 1) *
10203
- Math.max(lowerBounds != null ? lowerBounds.length : 1, upperBounds != null ? upperBounds.length : 1);
10240
+ Math.max(lowerBounds.length, upperBounds.length);
10204
10241
  const scansPerArrayElement = totalScans / (arrayValues != null ? arrayValues.length : 1);
10205
10242
  const indexRanges = [];
10206
10243
  for (let i = 0; i < totalScans; ++i) {
10207
10244
  const arrayValue = arrayValues
10208
10245
  ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])
10209
10246
  : EMPTY_VALUE;
10210
- const lowerBound = lowerBounds
10211
- ? this.generateLowerBound(indexId, arrayValue, lowerBounds[i % scansPerArrayElement], lowerBoundInclusive)
10212
- : this.generateEmptyBound(indexId);
10213
- const upperBound = upperBounds
10214
- ? this.generateUpperBound(indexId, arrayValue, upperBounds[i % scansPerArrayElement], upperBoundInclusive)
10215
- : this.generateEmptyBound(indexId + 1);
10216
- indexRanges.push(...this.createRange(lowerBound, upperBound, notInValues.map((notIn // make non-nullable
10217
- ) => this.generateLowerBound(indexId, arrayValue, notIn,
10218
- /* inclusive= */ true))));
10247
+ const lowerBound = this.generateLowerBound(indexId, arrayValue, lowerBounds[i % scansPerArrayElement], lowerBoundInclusive);
10248
+ const upperBound = this.generateUpperBound(indexId, arrayValue, upperBounds[i % scansPerArrayElement], upperBoundInclusive);
10249
+ const notInBound = notInValues.map(notIn => this.generateLowerBound(indexId, arrayValue, notIn,
10250
+ /* inclusive= */ true));
10251
+ indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));
10219
10252
  }
10220
10253
  return indexRanges;
10221
10254
  }
@@ -10229,25 +10262,38 @@ class IndexedDbIndexManager {
10229
10262
  const entry = new IndexEntry(indexId, DocumentKey.empty(), arrayValue, directionalValue);
10230
10263
  return inclusive ? entry.successor() : entry;
10231
10264
  }
10232
- /**
10233
- * Generates an empty bound that scopes the index scan to the current index
10234
- * and user.
10235
- */
10236
- generateEmptyBound(indexId) {
10237
- return new IndexEntry(indexId, DocumentKey.empty(), EMPTY_VALUE, EMPTY_VALUE);
10238
- }
10239
10265
  getFieldIndex(transaction, target) {
10240
10266
  const targetIndexMatcher = new TargetIndexMatcher(target);
10241
10267
  const collectionGroup = target.collectionGroup != null
10242
10268
  ? target.collectionGroup
10243
10269
  : target.path.lastSegment();
10244
10270
  return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {
10245
- const matchingIndexes = indexes.filter(i => targetIndexMatcher.servedByIndex(i));
10246
- // Return the index that matches the most number of segments.
10247
- matchingIndexes.sort((l, r) => r.fields.length - l.fields.length);
10248
- return matchingIndexes.length > 0 ? matchingIndexes[0] : null;
10271
+ // Return the index with the most number of segments.
10272
+ let index = null;
10273
+ for (const candidate of indexes) {
10274
+ const matches = targetIndexMatcher.servedByIndex(candidate);
10275
+ if (matches &&
10276
+ (!index || candidate.fields.length > index.fields.length)) {
10277
+ index = candidate;
10278
+ }
10279
+ }
10280
+ return index;
10249
10281
  });
10250
10282
  }
10283
+ getIndexType(transaction, target) {
10284
+ let indexType = 2 /* FULL */;
10285
+ return PersistencePromise.forEach(this.getSubTargets(target), (target) => {
10286
+ return this.getFieldIndex(transaction, target).next(index => {
10287
+ if (!index) {
10288
+ indexType = 0 /* NONE */;
10289
+ }
10290
+ else if (indexType !== 0 /* NONE */ &&
10291
+ index.fields.length < targetGetSegmentCount(target)) {
10292
+ indexType = 1 /* PARTIAL */;
10293
+ }
10294
+ });
10295
+ }).next(() => indexType);
10296
+ }
10251
10297
  /**
10252
10298
  * Returns the byte encoded form of the directional values in the field index.
10253
10299
  * Returns `null` if the document does not have all fields specified in the
@@ -10310,9 +10356,6 @@ class IndexedDbIndexManager {
10310
10356
  * queries, a list of possible values is returned.
10311
10357
  */
10312
10358
  encodeBound(fieldIndex, target, bound) {
10313
- if (bound == null) {
10314
- return null;
10315
- }
10316
10359
  return this.encodeValues(fieldIndex, target, bound.position);
10317
10360
  }
10318
10361
  /** Returns the byte representation for the provided encoders. */
@@ -10507,7 +10550,7 @@ class IndexedDbIndexManager {
10507
10550
  * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
10508
10551
  */
10509
10552
  createRange(lower, upper, notInValues) {
10510
- // The notIb values need to be sorted and unique so that we can return a
10553
+ // The notIn values need to be sorted and unique so that we can return a
10511
10554
  // sorted set of non-overlapping ranges.
10512
10555
  notInValues = notInValues
10513
10556
  .sort((l, r) => indexEntryComparator(l, r))
@@ -10553,6 +10596,20 @@ class IndexedDbIndexManager {
10553
10596
  }
10554
10597
  return ranges;
10555
10598
  }
10599
+ getMinOffset(transaction, target) {
10600
+ let offset;
10601
+ return PersistencePromise.forEach(this.getSubTargets(target), (target) => {
10602
+ return this.getFieldIndex(transaction, target).next(index => {
10603
+ if (!index) {
10604
+ offset = IndexOffset.min();
10605
+ }
10606
+ else if (!offset ||
10607
+ indexOffsetComparator(index.indexState.offset, offset) < 0) {
10608
+ offset = index.indexState.offset;
10609
+ }
10610
+ });
10611
+ }).next(() => offset);
10612
+ }
10556
10613
  }
10557
10614
  /**
10558
10615
  * Helper to get a typed SimpleDbStore for the collectionParents
@@ -12302,12 +12359,31 @@ function dbCollectionGroupKey(collectionGroup, offset) {
12302
12359
  }
12303
12360
  /**
12304
12361
  * Comparator that compares document keys according to the primary key sorting
12305
- * used by the `DbRemoteDocumentDocument` store (by collection path and then
12306
- * document ID).
12362
+ * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
12363
+ * and then document ID).
12364
+ *
12365
+ * Visible for testing.
12307
12366
  */
12308
12367
  function dbKeyComparator(l, r) {
12309
- const cmp = l.path.length - r.path.length;
12310
- return cmp !== 0 ? cmp : DocumentKey.comparator(l, r);
12368
+ const left = l.path.toArray();
12369
+ const right = r.path.toArray();
12370
+ // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
12371
+ let cmp = 0;
12372
+ for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {
12373
+ cmp = primitiveComparator(left[i], right[i]);
12374
+ if (cmp) {
12375
+ return cmp;
12376
+ }
12377
+ }
12378
+ cmp = primitiveComparator(left.length, right.length);
12379
+ if (cmp) {
12380
+ return cmp;
12381
+ }
12382
+ cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);
12383
+ if (cmp) {
12384
+ return cmp;
12385
+ }
12386
+ return primitiveComparator(left[left.length - 1], right[right.length - 1]);
12311
12387
  }
12312
12388
  /**
12313
12389
  * Schema Version for the Web client:
@@ -13704,7 +13780,7 @@ class LocalStoreImpl {
13704
13780
  this.mutationQueue = this.persistence.getMutationQueue(user, this.indexManager);
13705
13781
  this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.indexManager);
13706
13782
  this.remoteDocuments.setIndexManager(this.indexManager);
13707
- this.queryEngine.setLocalDocumentsView(this.localDocuments);
13783
+ this.queryEngine.initialize(this.localDocuments, this.indexManager);
13708
13784
  }
13709
13785
  collectGarbage(garbageCollector) {
13710
13786
  return this.persistence.runTransaction('Collect garbage', 'readwrite-primary', txn => garbageCollector.collect(txn, this.targetDataByTarget));
@@ -15446,10 +15522,30 @@ class MemoryEagerDelegate {
15446
15522
  * limitations under the License.
15447
15523
  */
15448
15524
  /**
15449
- * A query engine that takes advantage of the target document mapping in the
15450
- * QueryCache. Query execution is optimized by only reading the documents that
15451
- * previously matched a query plus any documents that were edited after the
15452
- * query was last listened to.
15525
+ * The Firestore query engine.
15526
+ *
15527
+ * Firestore queries can be executed in three modes. The Query Engine determines
15528
+ * what mode to use based on what data is persisted. The mode only determines
15529
+ * the runtime complexity of the query - the result set is equivalent across all
15530
+ * implementations.
15531
+ *
15532
+ * The Query engine will use indexed-based execution if a user has configured
15533
+ * any index that can be used to execute query (via `setIndexConfiguration()`).
15534
+ * Otherwise, the engine will try to optimize the query by re-using a previously
15535
+ * persisted query result. If that is not possible, the query will be executed
15536
+ * via a full collection scan.
15537
+ *
15538
+ * Index-based execution is the default when available. The query engine
15539
+ * supports partial indexed execution and merges the result from the index
15540
+ * lookup with documents that have not yet been indexed. The index evaluation
15541
+ * matches the backend's format and as such, the SDK can use indexing for all
15542
+ * queries that the backend supports.
15543
+ *
15544
+ * If no index exists, the query engine tries to take advantage of the target
15545
+ * document mapping in the TargetCache. These mappings exists for all queries
15546
+ * that have been synced with the backend at least once and allow the query
15547
+ * engine to only read documents that previously matched a query plus any
15548
+ * documents that were edited after the query was last listened to.
15453
15549
  *
15454
15550
  * There are some cases when this optimization is not guaranteed to produce
15455
15551
  * the same results as full collection scans. In these cases, query
@@ -15464,16 +15560,41 @@ class MemoryEagerDelegate {
15464
15560
  * - Queries that have never been CURRENT or free of limbo documents.
15465
15561
  */
15466
15562
  class QueryEngine {
15563
+ constructor() {
15564
+ this.initialized = false;
15565
+ }
15467
15566
  /** Sets the document view to query against. */
15468
- setLocalDocumentsView(localDocuments) {
15567
+ initialize(localDocuments, indexManager) {
15469
15568
  this.localDocumentsView = localDocuments;
15569
+ this.indexManager = indexManager;
15570
+ this.initialized = true;
15470
15571
  }
15471
15572
  /** Returns all local documents matching the specified query. */
15472
15573
  getDocumentsMatchingQuery(transaction, query, lastLimboFreeSnapshotVersion, remoteKeys) {
15473
- // Queries that match all documents don't benefit from using
15474
- // key-based lookups. It is more efficient to scan all documents in a
15475
- // collection, rather than to perform individual lookups.
15476
- if (matchesAllDocuments(query)) {
15574
+ return this.performQueryUsingIndex(transaction, query)
15575
+ .next(result => result
15576
+ ? result
15577
+ : this.performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion))
15578
+ .next(result => result ? result : this.executeFullCollectionScan(transaction, query));
15579
+ }
15580
+ /**
15581
+ * Performs an indexed query that evaluates the query based on a collection's
15582
+ * persisted index values. Returns `null` if an index is not available.
15583
+ */
15584
+ performQueryUsingIndex(transaction, query) {
15585
+ {
15586
+ return PersistencePromise.resolve(null);
15587
+ }
15588
+ }
15589
+ /**
15590
+ * Performs a query based on the target's persisted query mapping. Returns
15591
+ * `null` if the mapping is not available or cannot be used.
15592
+ */
15593
+ performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion) {
15594
+ if (queryMatchesAllDocuments(query)) {
15595
+ // Queries that match all documents don't benefit from using
15596
+ // key-based lookups. It is more efficient to scan all documents in a
15597
+ // collection, rather than to perform individual lookups.
15477
15598
  return this.executeFullCollectionScan(transaction, query);
15478
15599
  }
15479
15600
  // Queries that have never seen a snapshot without limbo free documents
@@ -15483,8 +15604,7 @@ class QueryEngine {
15483
15604
  }
15484
15605
  return this.localDocumentsView.getDocuments(transaction, remoteKeys).next(documents => {
15485
15606
  const previousResults = this.applyQuery(query, documents);
15486
- if ((hasLimitToFirst(query) || hasLimitToLast(query)) &&
15487
- this.needsRefill(query.limitType, previousResults, remoteKeys, lastLimboFreeSnapshotVersion)) {
15607
+ if (this.needsRefill(query, previousResults, remoteKeys, lastLimboFreeSnapshotVersion)) {
15488
15608
  return this.executeFullCollectionScan(transaction, query);
15489
15609
  }
15490
15610
  if (getLogLevel() <= LogLevel.DEBUG) {
@@ -15492,15 +15612,7 @@ class QueryEngine {
15492
15612
  }
15493
15613
  // Retrieve all results for documents that were updated since the last
15494
15614
  // limbo-document free remote snapshot.
15495
- return this.localDocumentsView.getDocumentsMatchingQuery(transaction, query, newIndexOffsetSuccessorFromReadTime(lastLimboFreeSnapshotVersion, INITIAL_LARGEST_BATCH_ID)).next(updatedResults => {
15496
- // We merge `previousResults` into `updateResults`, since
15497
- // `updateResults` is already a DocumentMap. If a document is
15498
- // contained in both lists, then its contents are the same.
15499
- previousResults.forEach(doc => {
15500
- updatedResults = updatedResults.insert(doc.key, doc);
15501
- });
15502
- return updatedResults;
15503
- });
15615
+ return this.appendRemainingResults(transaction, previousResults, query, newIndexOffsetSuccessorFromReadTime(lastLimboFreeSnapshotVersion, INITIAL_LARGEST_BATCH_ID));
15504
15616
  });
15505
15617
  }
15506
15618
  /** Applies the query filter and sorting to the provided documents. */
@@ -15519,6 +15631,7 @@ class QueryEngine {
15519
15631
  * Determines if a limit query needs to be refilled from cache, making it
15520
15632
  * ineligible for index-free execution.
15521
15633
  *
15634
+ * @param query The query.
15522
15635
  * @param sortedPreviousResults - The documents that matched the query when it
15523
15636
  * was last synchronized, sorted by the query's comparator.
15524
15637
  * @param remoteKeys - The document keys that matched the query at the last
@@ -15526,10 +15639,14 @@ class QueryEngine {
15526
15639
  * @param limboFreeSnapshotVersion - The version of the snapshot when the
15527
15640
  * query was last synchronized.
15528
15641
  */
15529
- needsRefill(limitType, sortedPreviousResults, remoteKeys, limboFreeSnapshotVersion) {
15530
- // The query needs to be refilled if a previously matching document no
15531
- // longer matches.
15642
+ needsRefill(query, sortedPreviousResults, remoteKeys, limboFreeSnapshotVersion) {
15643
+ if (query.limit === null) {
15644
+ // Queries without limits do not need to be refilled.
15645
+ return false;
15646
+ }
15532
15647
  if (remoteKeys.size !== sortedPreviousResults.size) {
15648
+ // The query needs to be refilled if a previously matching document no
15649
+ // longer matches.
15533
15650
  return true;
15534
15651
  }
15535
15652
  // Limit queries are not eligible for index-free query execution if there is
@@ -15540,7 +15657,7 @@ class QueryEngine {
15540
15657
  // the boundary of the limit itself did not change and documents from cache
15541
15658
  // will continue to be "rejected" by this boundary. Therefore, we can ignore
15542
15659
  // any modifications that don't affect the last document.
15543
- const docAtLimitEdge = limitType === "F" /* First */
15660
+ const docAtLimitEdge = query.limitType === "F" /* First */
15544
15661
  ? sortedPreviousResults.last()
15545
15662
  : sortedPreviousResults.first();
15546
15663
  if (!docAtLimitEdge) {
@@ -15556,6 +15673,22 @@ class QueryEngine {
15556
15673
  }
15557
15674
  return this.localDocumentsView.getDocumentsMatchingQuery(transaction, query, IndexOffset.min());
15558
15675
  }
15676
+ /**
15677
+ * Combines the results from an indexed execution with the remaining documents
15678
+ * that have not yet been indexed.
15679
+ */
15680
+ appendRemainingResults(transaction, indexedResults, query, offset) {
15681
+ // Retrieve all results for documents that were updated since the offset.
15682
+ return this.localDocumentsView
15683
+ .getDocumentsMatchingQuery(transaction, query, offset)
15684
+ .next(remainingResults => {
15685
+ // Merge with existing results
15686
+ indexedResults.forEach(d => {
15687
+ remainingResults = remainingResults.insert(d.key, d);
15688
+ });
15689
+ return remainingResults;
15690
+ });
15691
+ }
15559
15692
  }
15560
15693
 
15561
15694
  /**
@@ -21815,10 +21948,12 @@ class View {
21815
21948
  //
21816
21949
  // Note that this should never get used in a refill (when previousChanges is
21817
21950
  // set), because there will only be adds -- no deletes or updates.
21818
- const lastDocInLimit = hasLimitToFirst(this.query) && oldDocumentSet.size === this.query.limit
21951
+ const lastDocInLimit = this.query.limitType === "F" /* First */ &&
21952
+ oldDocumentSet.size === this.query.limit
21819
21953
  ? oldDocumentSet.last()
21820
21954
  : null;
21821
- const firstDocInLimit = hasLimitToLast(this.query) && oldDocumentSet.size === this.query.limit
21955
+ const firstDocInLimit = this.query.limitType === "L" /* Last */ &&
21956
+ oldDocumentSet.size === this.query.limit
21822
21957
  ? oldDocumentSet.first()
21823
21958
  : null;
21824
21959
  docChanges.inorderTraversal((key, entry) => {
@@ -21891,9 +22026,9 @@ class View {
21891
22026
  }
21892
22027
  });
21893
22028
  // Drop documents out to meet limit/limitToLast requirement.
21894
- if (hasLimitToFirst(this.query) || hasLimitToLast(this.query)) {
22029
+ if (this.query.limit !== null) {
21895
22030
  while (newDocumentSet.size > this.query.limit) {
21896
- const oldDoc = hasLimitToFirst(this.query)
22031
+ const oldDoc = this.query.limitType === "F" /* First */
21897
22032
  ? newDocumentSet.last()
21898
22033
  : newDocumentSet.first();
21899
22034
  newDocumentSet = newDocumentSet.delete(oldDoc.key);
@@ -27024,7 +27159,8 @@ function snapshotEqual(left, right) {
27024
27159
  * limitations under the License.
27025
27160
  */
27026
27161
  function validateHasExplicitOrderByForLimitToLast(query) {
27027
- if (hasLimitToLast(query) && query.explicitOrderBy.length === 0) {
27162
+ if (query.limitType === "L" /* Last */ &&
27163
+ query.explicitOrderBy.length === 0) {
27028
27164
  throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
27029
27165
  }
27030
27166
  }